Database Value in TextBox if Selected in ListBox in Windows Forms

Here I will explain putting database values into TextBoxes for a selected value in a list box. Before that I explain how to link a listbox with a database.

Step 1: Form

Drag and drop a listbox from the toolbox.

Dragging  a ListBox

Step 2: Code

Click on the list box and write this code:

 ListBox Code

private void listBox1.SelectedIndexChanged(object sender , EventArgs e)

{

    string str = "server = MUNESH\\SQL2008R2;Database=datastore;UID=sa;Password=123;";

    SqlConnection con = new SqlConnection(str);

    string query = "select * from tablename where name = '"+listBox1.text+"' ";

    SqlCommand cmd = new SqlCommand( query,con);

    sqldatareader dbr;

    try

    {

        con.open();

        dbr = cmd.executereader();

        while(dbr.read())

        {

            string sID = (string) dbr["ID"].tostring;

            string sname = (string) dbr["name"// name is string value

            string ssurname = (string) dbr["surname"]

            string sage = (string) dbr["age"].tostring;

            textbox1.text = sid;

            textbox2.text = sname;

            textbox3.text = ssurname ;

            textbox4.text = sage;

        }

    }

    catch(Execption es)

    {

        messagebox.show(es.message);

    }            

}

Step 3: Output

Run your application.

Adding String on Form

You can also go to my blog_munesh .

 


Similar Articles