1
votes

First off I would like to apologize as I am very new to C#. This may sound like a stupid question; however, I have not been able to find any examples anywhere on the internet or within the few books I have purchased on C#

I have a form that pulls quite a bit of data on load from a SQL Database. The First and Last names are inserted into two seperate comboBoxes one that will display the information as "First Last" and the other "Last, First" for easier browsing of names.

Thanks to some help on here the other day I learned how to populate a single textbox with the selected value of the comboBox. Thanks again for the assistance.

What I need to do is when a user is selected from the comboBox, all the information for that user will be displayed within certain textBoxes on the form. Example would be,

LastName = textBox1
FirstName = textBox2
MiddleName = textBox3

Do I need to write a seperate string for each of these fields, or can that data be pulled from one string that queries the SQL database for all data?

Any assistance you can provide would be greatly appreciated.

Here is what I have so far

enter code here

  namespace Tempus.Menus
 {
 public partial class Employees : Form
 {
    public Employees()
    {
        InitializeComponent();


        //Connect to database for Employees Table Headers
        SqlConnection myConnection = new SqlConnection(@"Server=Server4\INSTANCE;Integrated Security=true;" +
            "user id=userID;password=password;" +
            "Trusted_Connection=yes;" +
            "Database=Database;" +
            "connection timeout=30");

        try
        {
            myConnection.Open();
            string SqlDataPull = String.Format("SELECT * FROM Employees WHERE Lname IS NOT NULL {0}", (checkBox1.Checked ? "AND Active='Y'" : ""));
            //string SqlDataPull2 = String.Format("SELECT * FROM Employees WHERE Fname IS NOT NULL {0} ORDER By Fname", (checkBox1.Checked ? "AND Active='Y'" : ""));
            SqlCommand cmd = new SqlCommand(SqlDataPull, myConnection);
            cmd.CommandType = CommandType.Text;
            SqlDataReader dr = cmd.ExecuteReader();



            while (dr.Read())
            {
                string strEmployee = String.Format("{0}  {1}", dr["Fname"], dr["Lname"], dr["Mname"], dr["DOH"], dr["DOT"], dr["Active"], dr["DoNotRehireReason"], dr["PTO-balance"], dr["SNP-balance"], dr["Cred"]);

                comboBox1.Items.Add(strEmployee);

                string strEmployee2 = String.Format("{0}, {1}", dr["Lname"], dr["Fname"]);

                comboBox2.Items.Add(strEmployee2);

                int Fname = dr.GetInt32(0);
                string firstName = String.Format("{0}", dr["Fname"]);

            }


        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
        finally
        {
            if (myConnection != null)
            {
                myConnection.Dispose();
            }


        }
        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

        comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex == -1)
        {
            textBox1.Text = string.Empty;
        }
        else
        {

            textBox1.Text = comboBox1.SelectedItem.ToString();

        }
    }


    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox2.SelectedIndex == -1)
        {
            textBox1.Text = string.Empty;
        }
        else
        {

            textBox1.Text = comboBox2.SelectedItem.ToString();
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Employees_Load(object sender, EventArgs e)
    {

    }


    private void label1_Click(object sender, EventArgs e)
    {

    }






    private void button1_Click(object sender, EventArgs e)
    {
        Main myNewForm = new Main();

        myNewForm.Show();

        this.Close();
    }


    private void button2_Click(object sender, EventArgs e)
    {
        Reports myNewForm = new Reports();

        myNewForm.Show();

        this.Close();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox4_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox5_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox8_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox9_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox7_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox10_TextChanged(object sender, EventArgs e)
    {

    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked)

                {

            // logic here for if the box has now been checked


                }

            else

                {

                // what to do if the box has been unchecked


                }

       }
    }
}
3
@codingbiz: OK, Im' having trouble copying and pasting my code in this comment box..Chris Turner
Don't paste as a comment. Edit the original question..banging
Please separate your UI logic from Controller logic. Write them in two separate classesnawfal

3 Answers

2
votes

Based on the context you provided, here's my feedback. Please incorporate points which are applicable and ignore the rest. And hoping it answers your question too.

  • This is a single-tier application. Suggest to look at a layered structure (read more here) which is better in terms of maintainability, readability, etc.

  • Dynamic SQL is considered BAD in many aspects (including being a security risk), so look at the benefits stored by stored procedures (or LINQ-to-SQL or any ORM provider). This article is a good starting point.

  • You do a SELECT * FROM EMPLOYEE and read 10 (and possibly more) columns, but you use only the FName and LName columns. Suggest using something like SELECT FName, LName FROM EMPLOYEE (in a stored procedure or equivalent) and populate these into an object with the relevant properties in your data layer. In the UI layer, you can make one single call to fetch the data and bind the same data to both your combo-boxes with the appropriate format (one with space and the other with a comma).

  • Finally, have a second method in the data layer to fetch the details (all the columns mapped to correpsonding properties?) for a given employee (say based on last name). In the UI layer, based on the selected item in the combo-box, you can fetch the corresponding employee details and display it in your textboxes.

If you don't want to go this route and want a 'quick-fix', remember that the approach will be highly inefficient, tough to maintain and prone to security issues. Here, you just make the same database call again for the selected value in the combo-box (using a WHERE clause) and bind the details to your textboxes.

Hope this helps.

2
votes

I would recommend creating an Employee class

  class Employee
{
    public string firstName { get; set; }
    public string middleName { get; set;}
    public string lastName { get; set; }
    public string fullName { get; set; }

    //add other attributes here just the same...

    public Employee(string first, string middle, string last, string full)
    {
        firstName = first;
        middleName = middle;
        lastName = last;
        fullName = full;

        //assign ther other attributes..
    }


}

In which you can create list List<Employee> employees = new List<Employee>(); to add your returned SQL data into...

    SqlDataAdapter da = new SqlDataAdapter(SqlDataPull, myConnection); 
DataSet ds = new DataSet();
da.Fill(ds, "Employees");

foreach (DataRow row in ds.Tables["Employees"].Rows)
{
  employees.Add(dr["Fname"], dr["Lname"], dr["Mname"], dr["FullName"]);
}

You can return full name in your sql query RTRIM(Lname) + ',' + RTRIM(Fname) AS FullName

You can then add the list as the dataSource of your comboBoxes and reference the selected index to add the value to your text boxes.

1
votes

Not familiar with using SQL, however if you have all the information you need in the combobox than you can use the events you already have.

comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged; comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;

It looks to me like comboBox1 contains all the information on an employee and comboBox2 contains just the first and last name. Based on the while loop you use to populate the comboBoxes.

So if a user would click on a selection in comboBox1 in the SelectedIndexChanged you could do something like:

    if(comboBox1.SelectedIndex != -1)
    {
        string[]parts = comboBox1.Items[comboBox1.SelectedIndex].ToString().Split(' ');
        textBox1.Text = parts[0];//Index for First Name
        textBox2.Text = parts[1];//Index for Last Name
        textBox3.Text = parts[2];//Index for Middle Name
    }

Note: I used .Split(' ') which would split the string on spaces, but you use the character that is separating the different pieces of data when you retrieve the text from the combobox.

Not entirely sure of what you are trying to do with the SQL and such, but if you have the data in the comboboxes after you load from SQL you can easily get the pieces of data and place them into the appropriate textboxes without having to reload from the database.

Hope this helps.