如何修复列表框的问题 [英] How to fix problem with listbox

查看:55
本文介绍了如何修复列表框的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c#和sql中有一个数据库应用程序。有一个列表框,它使用数据库中的第一个名称字段与数据库绑定。但是,任何时候第一个名字都有相同的记录列表框会出错。

这是我的代码:

I have a database application in c# and sql. there is a listbox which is bind with the database using the first name field from the database. But anytime the first name has same records listbox gives an error.
this is my code :

SqlConnection con = new SqlConnection(@"Data Source=BROTHER-PC;Initial Catalog=iEMYS;Integrated Security=True");
            try
            {
                con.Open();
                string Query = "Select *from Teacher where [First Name] = '" + listBox1.Text + "'";
                SqlCommand createCommnad = new SqlCommand(Query, con);
                SqlDataReader dr = createCommnad.ExecuteReader();
                while (dr.Read())
                {
                    string sTeacherId = dr.GetInt32(0).ToString();
                    string sEMYSNO = dr.GetString(1);
                    string sTitle = dr.GetString(2);
                    string sFirstName = dr.GetString(3);
                    string sLastName = dr.GetString(4);
                    string sDateOfBirth = dr.GetDateTime(5).ToString();
                    string sSex = dr.GetString(6);
                    string sHometown = dr.GetString(7);
                    string sRegion = dr.GetString(8);
                    Boolean sSingle = dr.GetBoolean(9);
                    Boolean sMarried = dr.GetBoolean(10);
                    string sNameOfSpouse = dr.GetString(11);
                    Boolean sStudent = dr.GetBoolean(12);
                    string sInstitution = dr.GetString(13);
                    Boolean sEmployed = dr.GetBoolean(14);
                    string sProfession = dr.GetString(15);
                    Boolean sUnemployed = dr.GetBoolean(16);
                    string sTelephone1 = dr.GetString(17);
                    string sTelephone2 = dr.GetString(18);
                    string sEmail = dr.GetString(19);
                    string sPostalAddress = dr.GetString(20);
                    string sHomeAddress = dr.GetString(21);
                    string sHomeArea = dr.GetString(22);
                    Boolean sBaptism = dr.GetBoolean(23);
                    Boolean sConfirmation = dr.GetBoolean(24);
                    string sChurchStatus = dr.GetString(25);
                    string sPosition = dr.GetString(26);
                    Boolean sBrigade = dr.GetBoolean(27);
                    Boolean sChristLittleBand = dr.GetBoolean(28);
                    Boolean sGirlsFellowship = dr.GetBoolean(29);
                    Boolean sGuild = dr.GetBoolean(30);
                    Boolean sMenFellowship = dr.GetBoolean(31);
                    Boolean sSingingBand = dr.GetBoolean(32);
                    Boolean sSussanaWesley = dr.GetBoolean(33);
                    Boolean sWomenFellowship = dr.GetBoolean(34);
                    Boolean sYouthFellowship = dr.GetBoolean(35);


                    teacherIdTextBox.Text = sTeacherId;
                    titleComboBox.Text = sTitle;
                    eMYSNOTextBox.Text = sEMYSNO;
                    first_NameTextBox.Text = sFirstName;
                    last_NameTextBox.Text = sLastName;
                    date_Of_BirthDateTimePicker.Text = sDateOfBirth;
                    sexComboBox.Text = sSex;
                    hometownTextBox.Text = sHometown;
                    regionComboBox.Text = sRegion;
                    singleCheckBox.Checked = sSingle;
                    marriedCheckBox.Checked = sMarried;
                    name_Of_SpouseTextBox.Text = sNameOfSpouse;
                    studentCheckBox.Checked = sStudent;
                    institutionTextBox.Text = sInstitution;
                    employedCheckBox.Checked = sEmployed;
                    professionTextBox.Text = sProfession;
                    unemployedCheckBox.Checked = sUnemployed;
                    telephone__1MaskedTextBox.Text = sTelephone1;
                    telephone__2MaskedTextBox.Text = sTelephone2;
                    emailTextBox.Text = sEmail;
                    home_AddressTextBox.Text = sHomeAddress;
                    home_AreaTextBox.Text = sHomeArea;
                    postal_AddressTextBox.Text = sPostalAddress;
                    baptismCheckBox.Checked = sBaptism;
                    confirmationCheckBox.Checked = sConfirmation;
                    church_StatusComboBox.Text = sChurchStatus;
                    positionComboBox.Text = sPosition;
                    brigadeCheckBox.Checked = sBrigade;
                    christ_Little_BandCheckBox.Checked = sChristLittleBand;
                    girls_FellowshipCheckBox.Checked = sGirlsFellowship;
                    guildCheckBox.Checked = sGuild;
                    men_FellowshipCheckBox.Checked = sMenFellowship;
                    singing_BandCheckBox.Checked = sSingingBand;
                    sussana_WesleyCheckBox.Checked = sSussanaWesley;
                    women_FellowshipCheckBox.Checked = sWomenFellowship;
                    youth_FellowshipCheckBox.Checked = sYouthFellowship;


                    try
                    {
                        photoPictureBox.Image = null;
                        byte[] img = (byte[])(dr["photo"]);
                        if (img == null)
                        {
                            photoPictureBox.Image = null;
                        }
                        else
                            if (img != null)
                            {
                                MemoryStream ms = new MemoryStream(img);
                                ms.Seek(0, SeekOrigin.Begin);
                                photoPictureBox.Image = Image.FromStream(ms);
                            }
                    }
                    catch
                    {
                        MessageBox.Show("image not found", "Image Info");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            con.Close();

推荐答案

我猜你要么是一个没有经验的程序员或者由于某种原因,您已经从代码中删除了所有模块性。我会选择第一个选项,如果我在解释,你可以忽略我的建议。



我会给你的两个建议是1)创建一个类保留你的老师记录。 2)为你的编码添加了更多的模块化。



一般来说,如果我需要超过六行代码来完成一项任务,我会给它一个自己的方法。



您没有提到导致您发布的代码被调用的原因。我会假设当用户在列表框中选择一个值时会调用它。所以...



I'm guessing that either you are an inexperienced programmer or for some reason you have stripped all modularity out of your code. I'll go with the first option and you can ignore my suggestions if I'm over explaining.

Two suggestions that I would give you are 1) create a class to hold your teacher record(s). And 2) put a lot more modularity into your coding.

In general if I need more than half a dozen lines of code to accomplish a task I will give it its own method.

You did not mention what causes the code you posted to be called. I'll go on the assumption that it is called when the user selects a value in the list box. So...

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (comboBox1.SelectedIndex > 1)
        {
            GetAndLoadTeacher(comboBox1.Text);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}





因为获取和加载是两个非常不同的功能(其中一个与数据库交互,另一种形式),我使用两种方法。





Since getting and loading are two very different functionalities (one of them interacts with the database, the other with the form), I use two methods.

private void GetAndLoadTeacher(string text)
{
    Teacher people = GetTeacher(text);
    if (people != null)
        LoadPeople(people);
}










private void LoadPeople(Teacher people)
{
    first_NameTextBox.Text = people.FirstName;
    // ... etc
}







private Teacher GetTeacher(string text)
{
    SqlConnection con = new SqlConnection(@"Data Source=BROTHER-PC;Initial Catalog=iEMYS;Integrated Security=True");
    try
    {
        List<Teacher> teachers = new List<Teacher>();
        con.Open();
        string Query = "Select * from Teacher where [First Name] = '" + text + "'";
        SqlCommand createCommand = new SqlCommand(Query, con);
        SqlDataReader dr = createCommand.ExecuteReader();
        while (dr.Read())
        {
            Teacher teacher = new Teacher();
            teachers.Add(teacher);
            teacher.FirstName = dr.GetString(3);
            /// etc...
        }
        if (teachers.Count > 0)
        {
            if (teachers.Count == 1)
                return teachers[0];
            // you'll have to decide how to handle this condition.
            // I'd recommend passing more than just the first name
            // to the SQL
        }
    }
    catch
    {
        // handle error
    }
    return null;
}







这是你的老师班。






And here is your teacher class.

class Teacher
{
    public string FirstName { get; set; }
    // etc....
}







显然,这个类和两种方法都有很多你需要添加的属性。一旦您的代码更加模块化,您可能会遇到问题的解决方案。如果没有,请发布您看到的错误,以及代码中的错误点。




Obviously, the class and both methods have a lot more properties that you'll have to add. Once you get your code more modular, the solution to your problem may occur to you. If not, post what kind of error you are seeing, and at what point in the code it occurs.


这篇关于如何修复列表框的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆