Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ListBox
Hi Folks,
 
I have two listboxes and their corresponding data is stored in SQL Server. I am able to load the data of ListBox1 from SQL Server. But I am not able to populate the corresponding data of the selected item to ListBox 2 from ListBox 1.
 
Below is my code:
 

private void Form2_Load(object sender, EventArgs e)
        {
            cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
            cmd = new SqlCommand("SELECT * FROM new", cs);
 
            cs.Open();
            SqlDataReader dr;
            try
            {
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    listMemo.Items.Add(dr["memo"].ToString());
                }
            }
 
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
 
            finally
            {
                cs.Close();
            }
        }
 

private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
        {
            cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
            cmd = new SqlCommand("SELECT * FROM new WHERE memo='"+listMemo.SelectedItem+"'", cs);
 
            cs.Open();
            SqlDataReader dr;
            try
            {
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
 
                  ???
 

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

Please help me with this query.
 
Regards,
Nirmal
Posted 10-May-13 18:32pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi Nirmal
Please change your binding solution, your solution is not good solution so please review follow of links and use list box DataSource property for this purpose, if you have a any question after review these links please take a comment for me Wink | ;)
 
http://www.akadia.com/services/dotnet_databinding.html[^]
http://www.prodigyproductionsllc.com/articles/programming/bind-list-of-objects-to-listbox-in-c/[^]
 

Best Regards.
  Permalink  
Comments
Nirmal Gopalakrishnan at 11-May-13 3:16am
   
Thank you for your prompt response Aydin. I am still having issues with listbox. My query is simple.
This is the data in my database.
Table name : new

memo text
one onememo
two twomemo

Now, when do i a form load, i get all the text in memo displayed in listbox1. When i click on data in the listbox1, i should get the corresponding data in listbox 2. Ex: if i click on "one" i should get "onememo" in listbox 2.

Please advise.

--
NG
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Hi again
 
It is really easy just you should register SelectedIndexChanged event for listbox2 and make your query follow of :
 
void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string bindingQuerylistBox2 = string.Empty;
        bindingQuerylistBox2 = "select * from YourTable where relationId='yourvalue'" + listBox1.SelectedValue.ToString() + "'";
 
    }
 

and remmember you should use SelectedValue not SelectedItem
 
Best Regards.
  Permalink  
v2
Comments
Nirmal Gopalakrishnan at 11-May-13 5:05am
   
listYear -> name of the first listbox
listParty -> name of the second listbox
 
Date gets displayed in the first listbox (listYear) and when I click on the year on the first list box, the party name which is saved for that year should be displayed in the second list box (listParty). I tried the above code, but it is still not working.
 
private void listYear_SelectedIndexChanged(object sender, EventArgs e)
{
string query = string.Empty;
query = "SELECT partyname FROM casetab WHERE jdate='" + listYear.SelectedValue.ToString() + "'";

}
 
what do i write in :
 
private void listParty_SelectedIndexChanged(object sender, EventArgs e)
{

}
AYDIN EBRAHIMI HOMAY at 11-May-13 5:17am
   
jdate is a DataTime or nvacher ? my mean is data type of jdaye. and Please trace listYear_SelectedIndexChanged and be sure when you select the item you are get the real jdate value.
Nirmal Gopalakrishnan at 13-May-13 13:07pm
   
I did not get Aydin.
 
Hence i tried this:
 
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM new";
 
DataSet objDS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
 
cs.Open();
da.Fill(objDS);
 
cs.Close();
 
listMemo.ValueMember = "memo";
listMemo.DisplayMember = "memo";
listMemo.DataSource = objDS.Tables[0];

}
 

private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
{
int memo = Convert.ToInt32(listMemo.SelectedValue.ToString());
filltext(memo);
 
}
 

private void filltext(int memo)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT text FROM new WHERE memo = @memo";
cmd.Parameters.AddWithValue("@memo", listMemo);
 
DataSet objDS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
 
cs.Open();
da.Fill(objDS);
 
cs.Close();
 
if (objDS.Tables[0].Rows.Count >0)
{
listText.ValueMember = "text";
listText.DisplayMember = "text";
listText.DataSource = objDS.Tables[0];

}
 
}
 
Still it's not working.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

 private void Form2_Load(object sender, EventArgs e)
        {
            SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cs;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT memo FROM new";//It is not good idea "SELECT * FROM new"

            DataSet objDS = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
 
            //cs.Open();you don`t need to the open and close connection because the Adapter object do it automatically 
            da.Fill(objDS);
 
            //cs.Close();

            listMemo.ValueMember = "memo";
            listMemo.DisplayMember = "memo";
            listMemo.DataSource = objDS.Tables[0];
            
        }
 

        private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
        {
            int memo = Convert.ToInt32(listMemo.SelectedValue.ToString());
            filltext(memo);
 
        }
 
     
        private void filltext(int memo)
        {
            SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cs;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT text FROM new WHERE memo ='"+memo+"'";
           //cmd.Parameters.AddWithValue("@memo", listMemo); we don`t need it

            DataSet objDS = new DataSet();//you dont need dataset you can use datatable ;)
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
 
            //cs.Open(); 
            da.Fill(objDS);
 
            //cs.Close();

            if (objDS.Tables[0].Rows.Count >0)
            {
                listText.ValueMember = "text";
                listText.DisplayMember = "text";
                listText.DataSource = objDS.Tables[0];
            }
 
        }
 
It should be work right now Wink | ;)
  Permalink  
Comments
Nirmal Gopalakrishnan at 14-May-13 3:22am
   
no, it's still not working :(
 
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM new";
 
DataSet objDS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
 
// cs.Open();
da.Fill(objDS);
 
//cs.Close();
 
listMemo.ValueMember = "memo";
listMemo.DisplayMember = "memo";
listMemo.DataSource = objDS.Tables[0];

}
 

private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
{
// string memo = Convert.ToInt32(listMemo.SelectedValue.ToString());
if (listMemo.SelectedValue.ToString() != "")
{
string memo = Convert.ToString(listMemo.SelectedValue.ToString());
filltext(memo);
}

 
}
 

private void filltext(string memo)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT text FROM new WHERE memo = '"+memo+"'" ;
//cmd.Parameters.AddWithValue("@memo", listMemo);
 
DataSet objDS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
 
// cs.Open();
da.Fill(objDS);
 
// cs.Close();
 
if (objDS.Tables[0].Rows.Count >0)
{
listText.ValueMember = "text";
listText.DisplayMember = "text";
listText.DataSource = objDS.Tables[0];

}
 
}
AYDIN EBRAHIMI HOMAY at 14-May-13 5:19am
   
Please tell me what you get Error ?
Nirmal Gopalakrishnan at 14-May-13 10:28am
   
I do not get any error at all bro. The value doesn't get displayed in listbox 2 :(
Nirmal Gopalakrishnan at 15-May-13 0:50am
   
@Aydin: What to do now?
AYDIN EBRAHIMI HOMAY at 15-May-13 1:17am
   
We can sure our algorithm is the Ok but we have a problem at Select query could you trace filltext() method and send me result of cmd.commandtext value after adding memo from where condition?
Nirmal Gopalakrishnan at 15-May-13 10:28am
   
I used a breakpoint at cmd.CommandText = "SELECT memo FROM new"; and got the below Intellisense Results:
 
ADO.NET: Execute Reader "SELECT memo FROM new" The command text "SELECT memo FROM new" was executed on connection "Data Source=.\sqlexpress;Initial Catalog=details;UserId=sa;Password=P@ssw0rd",building a SqlDataReader.
 
ADO.NET: Execute Reader "SELECT text FROM new WHERE memo The command text "SELECT memo FROM new WHERE memo="" was executed on connection "Data Source=.\sqlexpress;Initial
Catalog=details;UserId=sa;Password=P@ssw0rd",building a SqlDataReader.
 

ADO.NET: Execute Reader "SELECT text FROM new WHERE memo The command text "SELECT memo FROM new WHERE memo="" was executed on connection "Data Source=.\sqlexpress;Initial
Catalog=details;UserId=sa;Password=P@ssw0rd",building a SqlDataReader.
Nirmal Gopalakrishnan at 15-May-13 11:45am
   
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT memo FROM new";
 
cs.Open();

SqlDataReader dr = cmd.ExecuteReader();
listMemo.Items.Clear();
 
int counter;
counter = 0;
 
while (dr.Read())
{
listMemo.Items.Add(dr["memo"]);
counter = counter + 1;

}
 
cs.Close();
dr.Close();
 

label1.Text = "Records Found: " + listMemo.Items.Count;
 

 

}
 
private void fillText(string memo)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("SELECT text FROM new WHERE memo='" + listMemo.SelectedItem.ToString() + "'");
listText.Items.Clear();

 
cs.Open();
 
SqlDataReader dr = cmd.ExecuteReader();
// listMemo.Items.Clear();
 
int counter;
counter = 0;
 
while (dr.Read())
{
listText.Items.Add(dr["text"]);
counter = counter + 1;
 
}
 
cs.Close();
dr.Close();
 
// label1.Text = "Records Found: " + listText.Items.Count;

}
 
private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
{
fillText(memo);
}
 
public string memo { get; set; }
Nirmal Gopalakrishnan at 15-May-13 11:47am
   
@Aydin: It finally worked with the above code :)
AYDIN EBRAHIMI HOMAY at 15-May-13 11:54am
   
Ok it is a good news
{ ADO.NET: Execute Reader "SELECT text FROM new WHERE memo The command text "SELECT memo FROM new WHERE memo="" was executed on connection "Data Source=.\sqlexpress;Initial
Catalog=details;UserId=sa;Password=P@ssw0rd",building a SqlDataReader. }
at here { "SELECT memo FROM new WHERE memo="" } we can see our query condition is empty and we have not any value after WHERE memo="value" so we have a problem in selected item in list box ;) try with this code :
listMemo.SelectedItem.ToString()
Please check this links it can be usefully :
http://msdn.microsoft.com/en-us/library/w67sdsex.aspx
AYDIN EBRAHIMI HOMAY at 15-May-13 12:19pm
   
Ok I am really happy just don`t forget accept green button please .... :)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT memo FROM new";
 
cs.Open();

SqlDataReader dr = cmd.ExecuteReader();
listMemo.Items.Clear();
 
int counter;
counter = 0;
 
while (dr.Read())
{
listMemo.Items.Add(dr["memo"]);
counter = counter + 1;

}
 
cs.Close();
dr.Close();
 

label1.Text = "Records Found: " + listMemo.Items.Count;
 

 

}
 
private void fillText(string memo)
{
SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("SELECT text FROM new WHERE memo='" + listMemo.SelectedItem.ToString() + "'");
listText.Items.Clear();

 
cs.Open();
 
SqlDataReader dr = cmd.ExecuteReader();
// listMemo.Items.Clear();
 
int counter;
counter = 0;
 
while (dr.Read())
{
listText.Items.Add(dr["text"]);
counter = counter + 1;
 
}
 
cs.Close();
dr.Close();
 
// label1.Text = "Records Found: " + listText.Items.Count;

}
 
private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
{
fillText(memo);
}
 
public string memo { get; set; }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 240
1 Kamal Rocks 184
2 BillWoodruff 173
3 PIEBALDconsult 160
4 CPallini 155
0 OriginalGriff 5,695
1 DamithSL 4,506
2 Maciej Los 4,007
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,180


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 15 May 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100