Saturday 19 April 2014

Link list box with DataBase in window form


                                                                                                                                               Previous..
                                                                                                                                                     Next..

Here i will explain How to connect ListBox with database.It is same as Link a combo Box with database.

Step(1):- Form
Drag and down a List box from Toolbox.
Step(2):- Code
Now make a function for filling the list box from database and call this method in constructor.


Void fillListBox()
{
    string str = "server = MUNESH\\SQL2008R2;Database=datastore;UID=sa;Password=123;";
    SqlConnection con = new SqlConnection(str);
    string query = "select * from tablename";
    SqlCommand cmd = new SqlCommand( query,con); 
    sqldatareader dbr;
    try
    {
        con.open();
        dbr = cmd.executereader();
        while(dbr.read())
        {
           string sname = (string) myreader["name"];; //name is coming from database
           Listbox1.items.Add(sname);
         }
         catch(execption es)
         {
              messagebox.show(es.message);
         } 
    }
}

Now call this method.
Public Form2()
{
InitializeComponent();
FillListBox();
}
Step(3):- Run 
Now Run your application
                                                                                                                                               Previous..
                                                                                                                                                     Next..

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...