1

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


                }

       }
    }
}
4

3 回答 3

2

根据您提供的上下文,这是我的反馈。请合并适用的要点并忽略其余部分。并希望它也能回答你的问题。

  • 这是一个单层应用程序。建议查看在可维护性、可读性等方面更好的分层结构(在此处阅读更多内容)。

  • 动态 SQL 在许多方面都被认为是不好的(包括存在安全风险),因此请查看存储过程(或 LINQ-to-SQL 或任何 ORM 提供程序)存储的好处。这篇文章是一个很好的起点。

  • 您做了 aSELECT * FROM EMPLOYEE并阅读了 10 个(可能更多)列,但您只使用了FNameandLName列。建议使用类似的东西SELECT FName, LName FROM EMPLOYEE(在存储过程或等效程序中)并将它们填充到具有数据层中相关属性的对象中。在 UI 层中,您可以进行一次调用以获取数据并将相同的数据以适当的格式绑定到两个组合框(一个带有空格,另一个带有逗号)。

  • 最后,在数据层有第二种方法来获取给定员工的详细信息(所有列映射到相应的属性?)(比如基于姓氏)。在 UI 层,根据组合框中的选定项,您可以获取相应的员工详细信息并将其显示在您的文本框中。

如果您不想走这条路并想要“快速修复”,请记住该方法效率极低,难以维护并且容易出现安全问题。在这里,您只需为组合框中的选定值再次调用相同的数据库(使用WHERE子句)并将详细信息绑定到您的文本框。

希望这可以帮助。

于 2012-07-23T19:07:26.663 回答
2

我建议创建一个 Employee 类

  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..
    }


}

您可以在其中创建列表List<Employee> employees = new List<Employee>();以将返回的 SQL 数据添加到...

    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"]);
}

您可以在 sql 查询中返回全名RTRIM(Lname) + ',' + RTRIM(Fname) AS FullName

然后,您可以将列表添加为组合框的数据源,并引用所选索引以将值添加到文本框中。

于 2012-07-23T19:12:05.737 回答
1

不熟悉使用 SQL,但是如果您在组合框中拥有所需的所有信息,则可以使用已有的事件。

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

在我看来,comboBox1 包含有关员工的所有信息,而 comboBox2 仅包含名字和姓氏。基于您用来填充组合框的 while 循环。

因此,如果用户单击 SelectedIndexChanged 中 comboBox1 中的选择,您可以执行以下操作:

    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
    }

注意:我使用 .Split(' ') 将字符串拆分为空格,但是当您从组合框中检索文本时,您使用分隔不同数据片段的字符。

不完全确定您要尝试使用 SQL 等做什么,但是如果您在从 SQL 加载后在组合框中有数据,您可以轻松获取数据并将它们放入适当的文本框中,而无需重新加载数据库。

希望这可以帮助。

于 2012-07-23T19:18:35.710 回答