none
Clear ComboBox Items RRS feed

  • Question

  • Hi ,

    recently i am working on a project but facing a problem . in winforms it worked well but in wpf its giving a headache . i have comboboxes which are bound to database . whenever i want to clear the combobox items i am getting null exception .

    lets say its a library management system . the project uses tabcontrol . if for the first time i am clicking on Retrun tab the grid loads fine and the also the combobox . now the problem arises when i am again clicking the Return tab . the combobox which is bind to a hashtable doesnt refreshes and gets me a null exception when i click Return button . what should i do ?

     

    Dipayan Sukul

    Monday, November 28, 2011 7:19 PM

Answers

  • Hi DIPAYAN,

    Thank you for your reply. Sorry for my misunderstanding and late reply.

    In you SelectionChanged event and other event, you almost need to use cmbbooks and its property. It is not allow in VS, because other event need to use it, if you clear it, exception will be raised in other events. So you need to  access and modify elements with     ItemsControl.ItemsSource instead.

    ItemsSouceName.Clear(); instead of cmbbooks.Items.Clear();

    If you have any additional questions, please feel free to let me know.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us
    Wednesday, December 7, 2011 8:52 AM
    Moderator

All replies

  • Do you have a sample of the code?  Are you setting the ItemsSource property of this combo box to the hashtable?  Do you reset this property whenever the user clicks on a different tab?  Would there be a case where you would not return any data from the hashtable?


    Christine A. Piffat
    Monday, November 28, 2011 9:53 PM
  • Hi DIPAYAN,

    Thank you for your post.

    According to your description, I understand when you clear a ComboBox, an exception been thrown.

    I don’t know much about your ComboBox, there are various possibilities may cause your issue.

    1.      Do you bind the SelectedItem property to someone value which could not be null?

    2.       As you said, the first time you click the Return tab, it is work fine, and after you click the Return tab again, the exception throw. That is to say the exception thrown when you second time to clear the ComboBox, right?  How do you clear the Items? If you use Comboname.Items.Clear() method, that will be Ok. But if you clear the item use Comboname.Items.RemovedAt(0);

    We need some additional information here to be able to determine what is going on. Could you kindly offer more details about your issue? It would be appreciated if you could offer a simple ready-to-run sample for us. You could upload it to SkyDrive space and post a link here.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us
    Wednesday, November 30, 2011 9:14 AM
    Moderator
  • Hi Experts ,

     

    I am giving the codes to give you a better view of my problem .

     

    //This is the code when the return button is clicked
    
    private void btnreturn_Click(object sender, RoutedEventArgs e)
            {
                bool IsSuccess = false;
                try
                {
    
                    string selIndex = cmbreturn.SelectedIndex.ToString();
                    string BookIssueId = "";
                    string BookId = "";
                    string SelectedIds = "";
                    int Bookindex = -1;
                    IDictionaryEnumerator myEnumerator = IDTable.GetEnumerator();
                    while (myEnumerator.MoveNext())
                    {
                        if (selIndex.Equals(myEnumerator.Key.ToString()))
                        {
                            SelectedIds = myEnumerator.Value.ToString();
                            break;
                        }
                    }
                    Bookindex = SelectedIds.IndexOf("~");
                    if (Bookindex != -1)
                    {
                        BookId = SelectedIds.Substring(0, Bookindex);
                        BookIssueId = SelectedIds.Substring(Bookindex + 1, SelectedIds.Length - (Bookindex + 1));
                    }
                    IsSuccess = Globals.ReturnBook(Convert.ToInt32(BookId),Convert.ToInt32(BookIssueId),DateTime.Parse(dtpretdt.Text),int.Parse(txtdatdiff.Text),int.Parse(txtfine.Text),txtrname.Text);
    
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message.ToString(), "Library Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (!IsSuccess)
                {
                    System.Windows.Forms.MessageBox.Show("Some error has occured", "Library Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Book Returned Succesfully.", "Library Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //canvas11.Visibility = System.Windows.Visibility.Hidden;
                    cmbbooks.Items.Clear();
                    Globals.MemberList[txtrname.Text] = Convert.ToInt32(Globals.MemberList[txtrname.Text]) - 1;
                   // Globals.BookList[cmbreturn.SelectedItem.ToString() + "~" + txtAuthor.Text + "#" + txtCat.Text] =
                        //Convert.ToInt32(Globals.BookList[txtrisbn.Text + "~" + txtrbname.Text + "#" + txtCat.Text]) + 1;
    
                }
            }

    //The other Related codes
    
    private void cmbreturn_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                SqlConnection conn = new SqlConnection(Globals.ConnectionString);
                conn.Open();
                SqlCommand sqlCom = new SqlCommand("select * from memberreg where memid=@id", conn);
                sqlCom.Parameters.Add(new SqlParameter("@id", cmbreturn.SelectedItem.ToString()));
                SqlDataReader reader = sqlCom.ExecuteReader();
                while (reader.Read())
                {
                    txtrname.Text = reader[2].ToString();
                }
                
    
                try
                {
                    DataSet ds = Globals.PopulateReturnBooks(txtrname.Text);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        btnreturn.IsEnabled = true;
                        int count = ds.Tables[0].Rows.Count - 1;
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            BookDetail.Add(i + "*" + ds.Tables[0].Rows[i][2].ToString() + "~" + ds.Tables[0].Rows[i][3].ToString() + "#" + ds.Tables[0].Rows[i][4].ToString(), ds.Tables[0].Rows[i][5].ToString() + "@" + ds.Tables[0].Rows[i][6].ToString() + "$" + ds.Tables[0].Rows[i][7].ToString());
                            IDTable.Add(count, ds.Tables[0].Rows[i][0].ToString() + "~" + ds.Tables[0].Rows[i][1].ToString());
                            count--;
                        }
    
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("No book Issued", "Library Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnreturn.IsEnabled = false;
                        return;
                    }
                    if (BookDetail != null && BookDetail.Count > 0)
                    {
                        IDictionaryEnumerator myEnumerator = BookDetail.GetEnumerator();
                        while (myEnumerator.MoveNext())
                        {
                            string Key = myEnumerator.Value.ToString();
                            int Bookindex = Key.IndexOf("@");
                            if (Bookindex != -1)
                            {
                                string BookTitle = Key.Substring(0, Bookindex);
                                cmbbooks.Items.Add(BookTitle);
                            }
                        }
                    }
                    cmbbooks.SelectedIndex = - 1;
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
                }
            }
    
            private void cmbbooks_GotFocus(object sender, RoutedEventArgs e)
            {
                if (cmbbooks.Text != "")
                {
                    SqlConnection conn = new SqlConnection(Globals.ConnectionString);
                    SqlCommand command = new SqlCommand("select * from books where bname=@id", conn);
                    conn.Open();
                    command.Parameters.Add(new SqlParameter("@id", cmbbooks.SelectedItem.ToString()));
                    SqlDataReader rdr = command.ExecuteReader();
                    while (rdr.Read())
                    {
                        txtrisbn.Text = rdr[1].ToString();
                    }
                }
             }
    
            private void cmbbooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                IDictionaryEnumerator myEnumerator = BookDetail.GetEnumerator();
                while (myEnumerator.MoveNext())
                {
                    string Value = myEnumerator.Value.ToString();
                    int Bookindex = Value.IndexOf("@");
                    if (Bookindex != -1)
                    {
                        string BookTitle = Value.Substring(0, Bookindex);
                        if (!BookTitle.Equals(cmbbooks.SelectedItem.ToString()))
                            continue;
                        Value = Value.Substring(Bookindex + 1, Value.Length - (Bookindex + 1));
                        int Categoryindex = Value.IndexOf("$");
                        string AuthorName = Value.Substring(0, Categoryindex);
                        string CategoryName = Value.Substring(Categoryindex + 1, Value.Length - (Categoryindex + 1));
                        txtrdtiss.Text = AuthorName;
                        txtrdtret.Text = CategoryName;
                        dtpretdt.Value = System.DateTime.Now;
                        dtpretdt.IsEnabled = false;
                        txtdatdiff.IsReadOnly = true;
                        txtfine.IsReadOnly = true;
                    }
                }
                if (Convert.ToDateTime(txtrdtiss.Text) != Convert.ToDateTime(dtpretdt.Text))
                {
                    DateTime dt1 = Convert.ToDateTime(txtrdtret.Text);
                    DateTime dt2 = Convert.ToDateTime(dtpretdt.Text);
                    TimeSpan dt3 = dt2.Subtract(dt1);
                    txtdatdiff.Text = dt3.Days.ToString();
                    int d = Convert.ToInt32(txtdatdiff.Text);
                    float a = d * 7.00f;
                    txtfine.Text = a.ToString();
                }
                else
                {
                    txtdatdiff.Text = Convert.ToString(0);
                    txtfine.Text = Convert.ToString(0);
                }
            }
    

    //More codes 
    
    SqlConnection conn = new SqlConnection(Globals.ConnectionString);
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("select distinct mid from issuereturndtls", conn);
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        cmbreturn.Items.Add(rd[0].ToString());
                    }
                    cmbreturn.SelectedIndex = -1;
                    if (cmbreturn.Text != "")
                    {
                        SqlCommand com = new SqlCommand("select * from memberreg where memid=@id", conn);
                        com.Parameters.Add(new SqlParameter("@id", cmbreturn.SelectedItem.ToString()));
                        SqlDataReader sdr = com.ExecuteReader();
                        while (sdr.Read())
                        {
                            txtrname.Text = sdr[2].ToString();
                        }
                    }
    

    Thank You .

     

    Dipayan Sukul

    Wednesday, November 30, 2011 9:48 AM
  • Hi Dipayan ,

    Thank you for your reply.

    The code your posted above is Windows Form, right?

    Due to Windows Form code is very different from WPF code, please post a WPF code here, so that we can help you to find the root cause of your issue.

    Thank you for your understanding.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us
    Wednesday, November 30, 2011 2:48 PM
    Moderator
  • Hi Dipayan ,

    Thank you for your reply.

    The code your posted above is Windows Form, right?

    Due to Windows Form code is very different from WPF code, please post a WPF code here, so that we can help you to find the root cause of your issue.

    Thank you for your understanding.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us


    Hi Annabella ,

     

    This code is of WPF and not WINDOWS FORM . I know what I am posting or where I am posting . Maybe System.windows.forms.messagebox gave you a wrong indication .

    Thanks anyways :)

     

    Dipayan Sukul


    Wednesday, November 30, 2011 5:28 PM
  • Hi DIPAYAN,

    Thank you for your reply. Sorry for my misunderstanding and late reply.

    In you SelectionChanged event and other event, you almost need to use cmbbooks and its property. It is not allow in VS, because other event need to use it, if you clear it, exception will be raised in other events. So you need to  access and modify elements with     ItemsControl.ItemsSource instead.

    ItemsSouceName.Clear(); instead of cmbbooks.Items.Clear();

    If you have any additional questions, please feel free to let me know.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us
    Wednesday, December 7, 2011 8:52 AM
    Moderator