Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
<blockquote class="quote"><div class="op">Quote:</div>          try
            {
                if (cn.State.ToString() != "Open")
                    cn.Open();
                cmd = new SqlCommand("select Antibiotic,RectionA,RectionB  from Culture", cn);
                dr = cmd.ExecuteReader();

                for (int i = 0; i < 5; i++)
                {
                    dataGridView5.Rows.Add(dr["Antibiotic"].ToString());
                    dataGridView5.Rows.Add(dr["RectionA"].ToString());
                    dataGridView5.Rows.Add(dr["RectionB"].ToString());
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "eeee");
            }
            finally
            {
                cn.Close();
            }</blockquote>


What I have tried:

I want read data from sql server to my datagriedview 

but in datagriedview i have 3 columns

please help me 
Posted
Updated 4-Dec-18 8:03am
Comments
Richard MacCutchan 4-Dec-18 15:02pm    
Always check the return value in dr to see if you actually received any data.

Try using sqldataadapter[^]

SqlCommand cmd = new SqlCommand("select Antibiotic,RectionA,RectionB  from Culture", con);
           SqlDataAdapter da = new SqlDataAdapter(cmd);
           DataTable dt = new DataTable();
           da.Fill(dt);
           for (int i = 0; i < dt.Rows.Count; i++)
           {
               if (i < 5) {
                   DataRow row = dt.Rows[i];
                   dataGridView5.Rows.Add(row["Antibiotic"].ToString(), row["RectionA"].ToString(), row["RectionB"].ToString());
               }
           }

This will display only the top 5 rows as per your code logic, if you want to load all the data to gridview, remove the IF condition
 
Share this answer
 
It appears that dr is null after the query. You need to perform a check dr.HasRows before going into the loop. You need to use foreach rather than a for in your loop rather than assuming the number of rows.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900