简体   繁体   中英

Can't Load Data to ComboBox C#

I Inserted Data to ComboBox using Folloowing Code in FormLoad Block

try
{
    using (SqlConnection con = new SqlConnection(conString))
    {
        SelectCategoryComboBox.Items.Clear();
        string query = "SELECT CategoryName FROM CategoryTable";
        con.Open();
        SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
        while (sdr.Read())
        {
            SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
        }

    }
}
catch
{
    StatusLabel.Text = "An error occured while loading Data";
}
finally
{
    SelectCategoryComboBox.SelectedItem = null;
    SelectCategoryComboBox.SelectedText = "Choose Category";
}

it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form . I used the following code to Delete and Load the items to ComboBox after Deleting.

try
{
    String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
    String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        cmd.ExecuteNonQuery();
    }
    StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
    StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
    try
    {
        SelectCategoryComboBox.Items.Clear();
        String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {


            string query = "SELECT CategoryName FROM CategoryTable";
            con.Open();
            SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
            while (sdr.Read())
            {
                SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
            }

        }
    }
    catch
    {
        StatusLabel.Text = "An error occured while loading Data";
    }
    finally
    {
        SelectCategoryComboBox.SelectedItem = null;
        SelectCategoryComboBox.SelectedText = "Choose Category";
    }

code for Creating new item Given below

 if (CategoryNameText.Text == "")
            {
                StatusLabel.Text = "You have to provide a name to create a category";
            }
            else
            {
                String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
                String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
                try
                {
                    using (SqlConnection con = new SqlConnection(conString))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand(query, con);
                        cmd.ExecuteNonQuery();
                    }
                    StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";

                    try
                    {
                        using (SqlConnection scon = new SqlConnection(conString))
                        {
                            string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
                            SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
                            scon.Open();
                            DataSet ds = new DataSet();
                            da.Fill(ds, "CategoryTable");
                            SelectCategoryComboBox.ValueMember = "Categoryid";
                            SelectCategoryComboBox.DisplayMember = "CategoryName";
                            SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
                        }
                    }
                    catch
                    {
                        Thread.Sleep(3000);
                        StatusLabel.Text = "An Error Occured while Loading Data!";
                    }
                    finally
                    {
                        SelectCategoryComboBox.SelectedItem = null;
                        SelectCategoryComboBox.SelectedText = "Choose Category";
                    }
                    CategoryNameText.Focus();
                }
                catch
                {
                    Thread.Sleep(3000);
                    StatusLabel.Text = ("An ERROR occured While creating category!");
                }
                finally
                {
                    CategoryNameText.Text = "Enter Category Name";
                }

            }
        }

This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox , it does the Job ie it deletes and Load the Remaining items to ComboBox .but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox .

I find the problem occur in the following sentence.

String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";

I have two solutions.

First, Please set the Allow nulls for other field. Like the following: 在此处输入图片说明

Second, you can use the following code to replace the original code.

string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);

I found What went Wrong... Change Following Code

using (SqlConnection scon = new SqlConnection(conString))
                        {
                            string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
                            SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
                            scon.Open();
                            DataSet ds = new DataSet();
                            da.Fill(ds, "CategoryTable");
                            SelectCategoryComboBox.ValueMember = "Categoryid";
                            SelectCategoryComboBox.DisplayMember = "CategoryName";
                            SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
                        } 

To

using (SqlConnection con = new SqlConnection(conString))
                        {
                            SelectCategoryComboBox.Items.Clear();
                            string squery = "SELECT CategoryName FROM CategoryTable";
                            con.Open();
                            SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
                            while (sdr.Read())
                            {
                                SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
                            }

                        }

it Worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM