C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm planning to create a small gui which has several module gui's and when i'm clicked it i'd like to show it. But don't know what's the correct approach to do that.

Any help would be grateful. I added a small sketch to show.OpenWindow.png
0
I have a global variable named "Globals.ServerPre" with com class type "SpckCOMApp". When i'm trying to release object i have some issues.

  public static  void KillServerPre()
        {
            if (Globals.IsServerPreRunning)
            {
                try
                {
                    ReleaseComApp(Globals.ServerPre);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Pre instance couldn't killed!");
                }
                return;
            }

      }

Open in new window




In below code i've issue;
com = null;

Open in new window

doesn't work/ doesn't assigns the null value to variable and Globals.ServerPre continue to show as not null.

But if i changed it to Globals.ServerPre=null; it assigns the null value to variable.

  public static  void ReleaseComApp(object com)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(com);
                com = null;
                // Globals.ServerPre = null;
                Log.Information("Pre(Solver) instance successfully killed!");

            }
            catch (Exception ex)
            {
                Log.Error(ex, "Object: " + com.ToString() + " couldn't released!");
            }
            finally
            {
                GC.Collect();
            }

            return;

        }
0
In c#, how to read all child, not one by one?

string xmlString = "<people><firstname>John</firstname><lastname>John</lastname></people>";            

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);
            foreach (XmlNode node in xmlDoc.SelectNodes("//people"))
            {
                //how to loop and read all child?
            }

Open in new window

0
What I ultimately want is dynamically create controls depending upon the number I get from db.

 for (int intControlIndex = 0; intControlIndex < number returned from db; intControlIndex++)
{
add a label and hyperlink
add a panel
add few check boxes inside the panel
}

so if number returned from db = 2 I need the output something like this

I need the above items to be shown in same sequence that I have shown above.
0
I call the below function from my page_load section

 private void AddControls()
        {
            int checkBoxCount = 3;
            var newPanel = new Panel();
            var newLabel = new Label();
            var newTextbox = new TextBox();
           
            System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
           
           
            for (int intControlIndex = 0; intControlIndex < checkBoxCount; intControlIndex++)
            {

                // textbox needs a unique id to maintain state information
                createDiv.ID = "createDiv_" + intControlIndex;
                newTextbox.ID = "TextBox_" + intControlIndex;
                newPanel.ID = "newPanel_" + intControlIndex;
                newLabel.ID = "newLabel_" + intControlIndex;
                newLabel.Text = "New Label";
                form1.Controls.Add(createDiv);

                // add the label and textbox to the panel, then add the panel to the form
                newPanel.Controls.Add(newLabel);
                newPanel.Controls.Add(newTextbox);
                createDiv.Controls.Add(newPanel);

            }

        }



--- This is what gets created when i run my code


    <div id="createDiv_2"><div id="newPanel_2">
      <span id="newLabel_2">New Label</span><input name="TextBox_2" type="text" id="TextBox_2">
</div></div></form>


as you can see only one div is …
0
I need  to execute a program (caprpts.exe)  from any application  folder
to which the executable is installed by my user

I have the code below:

 private void standardPredefinedReportsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = Application.ExecutablePath;
            Process.Start(path + @"\caprpts.exe");
           // Process.Start(@"C:\TournamentTracker\TrackerUI\caprpts.exe");
        }

Open in new window


The third line of the code above ie

 Process.Start(@"C:\TournamentTracker\TrackerUI\caprpts.exe");

executes correctly . I want the 2 lines above to achieve the same effect as the third

On debug i got the  screen below

Debug Information
The actual error while running is shown below

Error screen during run
How can I run an executable residing in my application path


Thanks

Olukay
0
I've doubts in some aspects to creating wireframe of my tool.

I'll create a  tiny gui which allows users to connect to COM-interface, with that case i'll have only one instance of COM-interface and be able to use that COM connection on my other projects in same solution.

My question is other modules will have a gui and i wonder how can i open them? User should open the base gui to connect COM interface and then open the other gui? or do you suggest another approach to do that?

any suggestion / help would be grateful.
0
I have the following piece of code

 <td style="cursor: auto; text-align: center" onmouseover="ShowAccount('vv<%# Eval("acct_nbr") %>','<%# Eval("acct_nbr") %>' );"
                                onmouseout="ShowAccount('vv<%# Eval("acct_nbr") %>','<%# Eval("acct_nbr_mask") %>' );">
                                <div id="vv<%# Eval("acct_nbr") %>">
                                    <asp:Label ID="lblAccountNbr" runat="server"><a href='AccountExceptionUpload.aspx'><%# Eval("acct_nbr_mask")%></a></asp:Label>
                                </div>
                            </td>

as you can see I am masking hte account number and on mouse hover you can see the account number. what I am trying to do is when i hover my mouse on account number i also want it converted to a hyper link . i tried putting <a> in the label but that did not help.
0
I've below code to SelectFolderDialog in my previous vb.net application. I'm trying to implement it to c# but didn't succeeded.

Can anyone help me to convert it to C# or any additional solution would be grateful.

Public Class SelectFolderDialog
    Implements IDisposable

    ' Wrapped dialog
    Private OFD As System.Windows.Forms.OpenFileDialog = Nothing

    ''' <summary>
    ''' Initialize our Open File Dialog object
    ''' </summary>
    Public Sub New()
        OFD = New System.Windows.Forms.OpenFileDialog()

        With OFD
            .Filter = "Folders|" & vbLf
            .AddExtension = False
            .CheckFileExists = False
            .DereferenceLinks = True
            .Multiselect = False
        End With
    End Sub

#Region "Properties"

    ''' <summary>
    ''' Gets/Sets the initial folder to be selected. A value of Nothing or Emplty selects the current directory.
    ''' </summary>
    Public Property InitialDirectory() As String
        Get
            Return OFD.InitialDirectory
        End Get
        Set(value As String)
            OFD.InitialDirectory = CType(IIf(value Is Nothing OrElse value.Length = 0, Environment.CurrentDirectory, value), String)
        End Set
    End Property

    ''' <summary>
    ''' Gets/Sets the title to show in the dialog. A value of Nothing or Empty defaults to 'Select a folder'
    ''' </summary>
    Public Property Title() As String
        Get
            Return OFD.Title
        End Get
        

Open in new window

0
In my javascript I want to check if a button is enabled or disabled. how can i do that.
0
I am converting my visual basic 6 application  to c#.
While in Visual basic 6  i wrote my reports with Crystal Report 11

Now i need to move these report to the crystal reports in my c# application which is
crystal report 13

I have all the forms and designer files ( including the ttx field definition file ) done under crystal report 11

QUESTIONS

1. Is there a path/tool  to migrate my old crystalreport11  file to crystalreport13  or do i have to rewrite all the reports again

2.  my app.config file in my c# application has the line:
<connectionStrings>
    <add name="Tournaments" connectionString="Host = 127.0.0.1; Database = Tournaments; Port = 5432; Username = postgres; Password = manager" />
  </connectionStrings>

How can i make my crystal report recognize this setting so that i do not have to be specifying connection string in
each report.
I just want to be able to get the designer, work on it and run .  it should recognize the app.config setting automatically

the same way my c#  forms behave

Thanks

Olukay
0
I have a pop up screen with save and cancel button.
When the user clicks on cancel button I want to do the following

if (allconditionstrue)
{
show confirm message box.
if the user clicks yes , close the pop up
if user clicks no, close the message box and keep pop up open.
}
else
{
close pop up
}
0
Building on previous  Questions  

I've been learning how to use ADO.NET Entity Data Model in a WinForms Using a movie Database I've included the model bellow

So far I've succeeded in doing select and updates I now need to add new data, Ultimately I'll need to add a new movie but that's to complex to start with

So Given File(s) can be associated with a movie via the   movielinkfile Database Table

How do I add a file and link it to a movie?

In SUDO code you'd
1 check file doesn't exists
2 Add the file.path Keep last ID
3 add entry to movielinkfile  with Last File ID & Movie ID

In .Net I'm assuming you create a File object see bellow but It doesn't like movie.id?

        private void AddFileBtn_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.InitialDirectory = MediaFiles;
            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                    if (File.Exists(file))
                    {
                        int FileID = CheckFileDB(file);
                        if (FileID == 0)
                        {
                            AddFileToDB(SelectedMovieID, file);
                        }


                    }
                

Open in new window

0
I am trying to read  a date  field into my model
I have a postgresql database and i am doing the read from
a c# method  (see the code below)

[]{
                        LoansDetailModel model = new LoansDetailModel();

                        if ((string)reader["ent_code"] != null)
                        {
                            //model.Id = (int)reader["id"]; //id is the column name in the database
                            model.staff_no = (string)reader["staff_no"]; //absecode is the column name in the database
                            model.ent_code = (string)reader["ent_code"]; //absedesc is the column name in the database
                            model.loanid = Convert.ToInt32(reader["loanid"]);
                            //model.date_taken = (DateTime)reader["date_taken"];
                            model.date_taken = DateTime.ParseExact("date_taken", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
                            model.amt_taken = (decimal)(reader["amt_taken"]);
                          //  model.ded_date = Convert.ToDateTime(reader["ded_date"]);
                            model.date_taken = DateTime.ParseExact("ded_date", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
                            model.amt_left = (decimal)reader["amt_left"];
                            model.amt_paid = (decimal)reader["amt_paid"];
                            model.amtpay_todate = …
0
I have buttons using URL.Action and cannot get them to open in a new tab.  I've tried target=_blank with no luck!

 <button class="btn btn-info" style ="width:90px;" onclick="location.href='@Url.Action("LocationDetails", "Location", new
                                                                                                                 { id = @Model.id                                                                                                 
                                                                                                                 }
                                                                                         
                                )'">
                                Details
                            </button>

Open in new window

0
How do you ensure a line of text has been selected?

In the mock up below on pressing the button a Line of text is written to a text box

However if no line has been actually selected IE user has not clicked in the RichTextBox the fist line is written

How do you ensure a user  has actually chosen a line?

Also a line of text could be longer then the RichTextBox width is it possible, on hover, to show the whole line in some kind of pop up label?  

BTW: In the Real App the lines in the RichTextBox will be file paths so using word wrap not really an option

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace TestForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
            richTextBox1.AllowDrop = true;
            richTextBox1.AutoWordSelection = false;

        }

        private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Rtf))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
        private void richTextBox1_DragDrop(object sender, 

Open in new window

0
Hi Experts.

Need help in converting the usage of the foreach to using a lamda expression to get the list of pets.

 //Looking for something like this acutalPets = people............ToList();

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;

namespace SampleTest
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Location> Locations { get; set; }
    }

    public class Location
    {
        public string PetType { get; set; }
        public bool HasPets { get; set; }
    }

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            //Arrange
            List<Person> people = new List<Person>() {
                new Person() {FirstName = "FirstName01", LastName = "LastName01",
                              Locations = new List<Location>() {
                                  new Location() { HasPets = false}
                              }
                },
                new Person() {FirstName = "FirstName02", LastName = "LastName02",
                              Locations = new List<Location>() {
                                  new Location() { PetType = "Dog", HasPets = true }
                              }
                },
                new Person() {FirstName = "FirstName03", LastName = "LastName03",
                              

Open in new window

0
I have a datagridview on my C# form. Recently I have noticed a few times were there are not enough rows to fill the form so the vertical slider does not appear. Looking for solutions I have found there is no property of the dgv to force the vertical slider. I keep seeing things about creating a custom dgv. Is there anyway to force, or at least appear to force, a vertical slider on an already existing dgv?

My dgv is called dgvDistributions.
1
Hello Experts,

I have an issue with C# List, when I add values it showing the duplicates data.

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		Student std = new Student();
		List<Student> studentList = new List<Student>();
		
		std.ID = 1;
		std.Name = "John";
		studentList.Add(std);
		
		
		std.ID = 2;
		std.Name = "Doe";
		studentList.Add(std);	
		
		
		Console.WriteLine(studentList.Count);//count
		
		Console.WriteLine(studentList[0].ID); //ID
		Console.WriteLine(studentList[0].Name); //Name
	}
}

public class Student
{ 
	public int ID { get; set; }
	public string Name { get; set; }
}

Open in new window


Output:
2
2
Doe

The count was correct, but I was expecting below output and the list shows duplicates:

2 -- >Count
1 --> ID
John -- > Name

Please help, what I was doing incorrect.

Thanks,
ASPDEV
0
I'm trying to work out how to drag and drop File(s) into a rich text box and grab file Path

The code bellow works however Why dose a file object also appear in the RichTextBox (This is related to which ever file your dragging, if more than 1 it's which ever you happen to of clicked on in Windows Explorer



FileDrop.JPG
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace TestForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //this.richTextBox1.AllowDrop = true;
            //this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
            //this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);
            richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
            richTextBox1.AllowDrop = true;

        }

        private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Rtf))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
        private void richTextBox1_DragDrop(object sender, 

Open in new window

0
Hello,
If anyone knows  in Csharp,how to convert string such as "1.0.2" to decimal or double. I tried below but it gives error.

Convert.ToDecimal("1.0.2")

'Convert.ToDecimal("1.0.2")'
threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "Input string was not in a correct format."
    Source: "mscorlib"
    StackTrace: "   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)\r\n   at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)\r\n   at System.Convert.ToDecimal(String value)"
    TargetSite: {Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuffer ByRef, System.Globalization.NumberFormatInfo, Boolean)}
0
Need help to convert below C++ code to C#. Thanks for the help.

In C++:
double dValue = 14 / 1000;
ostringstream oss;
oss.precision(10);
oss<<fixed<<dValue;
string sValue = oss.str();
1
Hi

I have a movie database populated from TMDB api

On the main form each actor is generated by a User Control
Clicking the actors name sends both Actor Name and database person id to  People Search form
When I click the update button on the People Search form this should update the database

How do i update the UC on the main form?

Person search form
        private void PersonUpdateBTN_Click(object sender, EventArgs e)
        {
            using (var context = new MoviesEntities())
            {
                var results = context.people.SingleOrDefault(p => p.id == PersonID);
                if (results != null)
                {
                    results.name = ActorName;
                    results.tmdb_id = TMDB_id;
                    results.profile_path = profile_path;
                 //   context.SaveChanges();
                }
            }

        }

        private void OKbtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

Open in new window


Main Form
        private void GetCast(int id)
        {
            using (var context = new MoviesEntities())
            {
                var Movies =  context.movielinkpersons.Where(p => p.movieId == id).OrderBy(mp => mp.role) .ToList();
                foreach(var movielinkperson in Movies)
                {
                    var person = movielinkperson.person;
                    

                    var actorBox = new ActorBox(person);
                    

Open in new window

0
Hello Experts,
I have this piece of code in Visual CS

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C NET USER" ;
            process.StartInfo = startInfo;
            process.Start();

            startInfo.Arguments = "/C copy " + (char)34 + "D:\\_ms2\\02 FamBZP\\Lalita\\DNI_LALITA_29325453.jpg" + (char)34 + " " + (char)34 + "C:\\tmp\\ftp\\aaaaaaa.jpg" + (char)34;
            startInfo.Arguments = "/C copy " + (char)34 + "D:\\_ms2\\02 FamBZP\\Lalita\\DNI_LALITA_29325453.jpg" + (char)34 + " " + (char)34 + "C:\\tmp\\ftp\\BBBBBBB.jpg" + (char)34;
            process.StartInfo = startInfo;
            process.Start();

            System.Diagnostics.Process.Start("CMD.EXE", "/C D:&cd \\temp&dir& pause");

How can I verify if each dos command was executed successfully?

The code works just fine, I would like to programmatically verify the success / errorlevel / output
Regards,
0
Starting with a string representing a range:
string sortRange = "C10:H24";

Open in new window

This then works:
worksheet.Range[sortRange].Sort(worksheet.Range[sortRange].Columns[1], xlSortOder.xlDescending);

Open in new window

I saw worksheet.Range[sortRange] was listed twice, so I decided to refactor that out:
Excel.Range r = worksheet.Range[sortRange];
Excel.Range c = r.Columns[1];
r.Sort(c, xlSortOrder.xlDescending);

Open in new window

My refactored version gives a much different result. Why is that?
1

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).