remove listbox valueid on selection of another listbox item

Category: c# language

Question

scottichrosaviakosmos on Sun, 09 Sep 2012 14:50:13


I have 2 listboxs. 1st one is data bound and secound one is populated by selecting 1st.
eg:
listbox1
 jenny
 rock
when i click listbox 1 items it also appear in listbox2. now when i click listbox1 item 2 things happen:
1. listbox2 populates with same item selected in   listbox1.
2. a textbox which gets valueid from listbox1 item select.

So now, when i try to remove item from listbox2 then itm should be removed from the list and the valueid in textbox related to the item should also be removed.

I have tried o do this by selecteditem property of listbox but it didn't work. since listbox1 is data bound but listbox2 is not.

Replies

Mitja Bonca on Sun, 09 Sep 2012 15:19:23


How do you pas data to listBox2? Simply my adding Items (listBox2.Items.Add("item"))?

So how do you try to remove the item (or items) from listBox2? 

Use:

 listBox2.Items.Remove(listBox2.SelectedItem.ToString());

and to remove id from textBox, simply set Text property to string.Empty or use textBox1.Text = "";

scottichrosaviakosmos on Sun, 09 Sep 2012 15:49:02


Thanks, but i am able to remove item from listbox2 but what ever i am deleting from listbox2 its valueid is in listbox1. Textbox has valueid geting from listbox1 since listbox2 is not data bound.

Mitja Bonca on Sun, 09 Sep 2012 16:06:21


Thanks, but i am able to remove item from listbox2 but what ever i am deleting from listbox2 its valueid is in listbox1. Textbox has valueid geting from listbox1 since listbox2 is not data bound.

I dont understand, sorry. What means bolded text? What is this valueid? Do you use a cusom class to fill some list<T> (or dataTable) and bind it to listBox1?

---

I dont actually see the problem of removing (deleting) item(s) from listBox2, and textBox. Please explain it BETTER!

BonnieB on Sun, 09 Sep 2012 16:44:01


Scott --- Could you post the relevant code?

scottichrosaviakosmos on Sun, 09 Sep 2012 19:04:14


Ok, let me explain in details.

I have a form which has 2 listboxs, textbox and 2 buttons.

lst1 and lst2.  Also has 2 buttons "add" and "Remove".

lst1 is populated from a database table  which has 2 fields : "Name" ad "emailid".

lst1 will show items "name" from table column "name". eg: ronny, danial...

when i select an item(name) in lst1 and click Add button then the name will be added in lst2(lst2 is not connected to datasource). Also the displayvalue member or emailid with respect to the name selected in lst1 will be added to the textbox.(this is working fine).

Now, when i select an item in lst2 which was added from lst1 and then click on Remove button then the item(name) should be removed from lst2(this is also working fine) and also the emailid corresponding to  the value(name) selected in lst2 should be removed from textbox.

emailid on selectitem of lst2 is not getting removes since the lst2 is connected to database. lst is adding its item from lst1.

I hope now the scenario is clear.!:|

Cheers

scottichrosaviakosmos on Sun, 09 Sep 2012 19:04:30


Ok, let me explain in details.

I have a form which has 2 listboxs, textbox and 2 buttons.

lst1 and lst2.  Also has 2 buttons "add" and "Remove".

lst1 is populated from a database table  which has 2 fields : "Name" ad "emailid".

lst1 will show items "name" from table column "name". eg: ronny, danial...

when i select an item(name) in lst1 and click Add button then the name will be added in lst2(lst2 is not connected to datasource). Also the displayvalue member or emailid with respect to the name selected in lst1 will be added to the textbox.(this is working fine).

Now, when i select an item in lst2 which was added from lst1 and then click on Remove button then the item(name) should be removed from lst2(this is also working fine) and also the emailid corresponding to  the value(name) selected in lst2 should be removed from textbox.

emailid on selectitem of lst2 is not getting removes since the lst2 is connected to database. lst is adding its item from lst1.

I hope now the scenario is clear.!:|

Cheers

BonnieB on Sun, 09 Sep 2012 19:36:54


Sort of clear, but I'll ask again ... could you please post the relevant code?

Mitja Bonca on Sun, 09 Sep 2012 20:09:33


You are not doint this correctly. I dont know what emailid has to do here - especially when removing items from listBox2. Apparently you add full object to the listBox2 (or I dont know what you do exactly when you add object from listBox1 to listBox2), but you are surely doing it wrong (since you didnt provide us any code - as Bonnie said it earlier).

I will now show you how you have to do to pull this off:

        public Form1()
        {
            InitializeComponent();
            listBox1.DataSource = GetDataForListBox();
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "EmailId";
        }

        private DataTable GetDataForListBox()
        {
            //this is your method to get the data from database

            //in my exmaple I will simply add some example data:
            DataTable table = new DataTable();
            {
                table.Columns.Add("EmailId", typeof(int));
                table.Columns.Add("Name", typeof(string));

                //adding some example rows:
                table.Rows.Add(1, "Name 1");
                table.Rows.Add(2, "Name 2");
                table.Rows.Add(3, "Name 3");
            }
            return table;           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataRowView view = listBox1.SelectedItem as DataRowView;
            string name = view["Name"].ToString();
            int emailId = int.Parse(view["EmailId"].ToString());
            listBox2.Items.Add(name);
            textBox1.Text = emailId.ToString();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox2.Items.Count > 0)
            {
                if (listBox2.SelectedIndex > -1)
                {
                    listBox2.Items.Remove(listBox2.SelectedItem.ToString());
                    textBox1.Text = "";
                }
                else
                    MessageBox.Show("To remove, please select a name from listBox2!");
            }
            else
                MessageBox.Show("There is no items email ids to remove (list is empty)!");
        }

scottichrosaviakosmos on Thu, 13 Sep 2012 07:05:45


Thanks, but this what i am already doing. Problem is that i am running a sql script which creates a table and insert name and emailid in that table and from that table i am geting data in my listbox1 but listbox2 is not bound to any datasoure and is total dependet on listbox1. when i click on add button then i am able to populate the textbox with emailid with respect to names selected in listbox1. but when i m clicking remove button then i want the items to be removed from listbox2 and also the respective email for that name also be removed from my textbox. this textbox adds emails and we are using textbox emails to replace a string in a textfile.so we need this textbox to be filled or items removed from it.

Mitja Bonca on Thu, 13 Sep 2012 07:23:34


... but when i m clicking remove button then i want the items to be removed from listbox2 and also the respective email for that name also be removed from my textbox. this textbox adds emails and we are using textbox emails to replace a string in a textfile.so we need this textbox to be filled or items removed from it.

Very unclear, every time you skeak up, you say something different, so how can we then figure out what exactly is that you want!

1. You want to remove all the items now from listbox2? Before was only selected item!

2. is textBox databound to selecrted items from listbox1? If not, then setting Text property to string.Empty will clear the textBox (same as two double quotes - Text = "";).

3. now you are saying that this same textBox is meat to add email (emails or ids??) to replace a string in text file - what strings in the file? This all is very unclear.

Tell us exactly what you want, when some control is pressed, selected, or what ever. 

You cound even try something by your self, regarding that this thread has been answer several times, regarding to the thread`s title, and the on description in your 1st post!! This is now how we do here on msdn forum. 


Mitja

scottichrosaviakosmos on Fri, 14 Sep 2012 06:22:58


Finally, i am now writing code.

private void button_Add_Click(object sender, EventArgs e)
        {
            DataRowView view = listBox1.SelectedItem as DataRowView;
            string item = view["name"].ToString();
            string value = Convert.ToString(view["emailid"]);
            
            if (listBox2.Items.Contains(item))
            {
                MessageBox.Show("Name already present in list");
            }
            else
            {
                listBox2.Items.Add(item);
                demo.Items.Add(listBox1.SelectedValue);
                txtemail.Text = "";
                foreach (object liItem in demo.Items)
                {
                    txtemail.Text += liItem + ";";
                }               
            }
        }

And this is which i want to achive:

private void button4_Click(object sender, EventArgs e)
        {
            listBox2.DataSource = listBox1.DataSource;
            listBox2.DisplayMember = listBox1.DisplayMember;
            listBox2.ValueMember = listBox1.ValueMember;
            DataRowView view = listBox2.SelectedItem as DataRowView;
            string item = view["name"].ToString();
            string value = Convert.ToString(view["emailid"]);
            listBox2.DataSource = null;
         listBox2.Items.Remove(listBox2.SelectedItem);
         //txtemail.Text = "";
         //foreach (object liItem in listBox2.Items)
         //{
         demo.Items.Remove(listBox2.SelectedItem);
             txtemail.Text = "";
             foreach (object liItem in demo.Items)
             {
                 txtemail.Text += liItem + ";";
                 //txtemail.Text = null;
             }
             //txtemail.Text += value.ToString() + ";";
           
         //}

        }

So , I want to remove the emails on selected item of listbox2.  Listbox2 is  connected to any datasource.

Let me put the code for listbox datasource also:

 private void FLoadListBox(string connstr)       
        {
            string strSql  = "Select name, emailid from  dbo.dbtesting Order by name";
            SqlConnection sqlconn = new SqlConnection(connstr);           
            sqlconn.Open();
            SqlDataAdapter sqlDA = new SqlDataAdapter(strSql, sqlconn);
            DataSet DS = new DataSet("DS");           
            try              
            {               
                DS.Clear();               
                DS.CaseSensitive = true;               
                sqlDA.Fill(DS,"Cust");               
                // fill listbox               
                this.listBox1.DisplayMember = "Cust.name";
                this.listBox1.ValueMember = "Cust.emailid";
                this.listBox1.DataSource = DS;               
                sqlconn.Close();              
            }           
                catch (SystemException MsgException)              
            {                          
                }              
        }

Hope , now it will be clear.

BonnieB on Fri, 14 Sep 2012 15:40:48


Seeing your code helps. I do wish you had posted it several days ago as I asked.

For starters, I think it might be easiest to use a DataTable to bind to listBox2, create one just for that purpose. It should be a member variable on your Form, so declare it at the top of the class:

// in your declarations
DataTable dtCust;

// after you Fill DS
DataSet dsSelected = DS.Clone(); // clones the schema, but not the data
this.dtCust = dsSelected.Tables["Cust"];
this.listBox2.DisplayMember = "name";
this.listBox2.ValueMember = "emailid";
this.listBox2.DataSource = this.dtCust;            

Then your button_Add_Click can be changed to this:

// button_Add_Click
DataRowView view = listBox1.SelectedItem as DataRowView;
string item = view["name"].ToString();
string value = view["emailid"].ToString();

// see if it's already there:
DataRow[] rows = this.dtCust.Select(string.Format("name = '{0}'", item)

if (rows.Length > 0)
{
    MessageBox.Show("Name already present in list");
}
else
{
    // by adding the row to dtCust, listBox2 will automatically show the new row
    this.dtCust.ImportRow(view.Row);

    // you haven't shown the definition of demo, so I'm guessing as to what it is
    demo.Items.Add(value);
    txtemail.Text = "";

    // should this be string instead of object?
    foreach (object liItem in demo.Items) 
    {
        txtemail.Text += liItem + ";";
    }                
}

I assume the button4_Click was for removing an item from listBox2 and your TextBox? Change it to this:

// button4_Click
DataRowView view = listBox2.SelectedItem as DataRowView;
string item = view["name"].ToString();
string value = view["emailid"].ToString();

// remove from the demo.Items, and this just a guess, not knowing how demo is defined
demo.Items.Remove(value)

// remove from the DataTable, removes from the listBox2
DataRow[] rows = this.dtCust.Select(string.Format("name = '{0}'", item)
int index = this.dtCust.Rows.IndexOf(rows[0]);
this.dtCust.Rows.RemoveAt(index);

// now, re-do your TextBox
txtemail.Text = "";
foreach (object liItem in demo.Items) 
{
    txtemail.Text += liItem + ";";
}                


~~Bonnie Berent DeWitt [C# MVP]

geek-goddess-bonnie.blogspot.com


scottichrosaviakosmos on Sat, 15 Sep 2012 07:58:40


This is working. Great GGB. Thanks.

Yup, one more question. I am a beginner in .net(programming) and i am just 18. What will be best way to learn programming faster and learning generic codding style.

Thanks again.

Cheers :)

BonnieB on Sat, 15 Sep 2012 18:43:30


Glad I could help you, Scott! I didn't realize you were "just a kid". ;0)

As far as best ways to learn, there's probably a gazillion answers to that question. I'm such an old fart that there was no such thing as personal computers when I was your age, so learning about "computer science" in general and "programming" in particular, is a lot different now than it used to be way back when I went to school. 

Anyway, I suggest you start a new thread with this question as you'd probably get a lot better answers than I could come up with. ;0)