Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My Database has 3 column are "Name", "Math", "Chemistry" and "Sum". I can query some rows by SQL in C#, but I don't know how to get the value from column to variable in C#. If anyone know, please help me!

For ex:

C#
SqlConnection con;
SqlCommand cm1;
DataSet ds;
SqlDataAdapter ap;

private void btn_info_Click(object sender, EventArgs e)
{
    cm1 = new SqlCommand("SELECT * FROM Database ", con);

    ap = new SqlDataAdapter(cm1);
    ds = new System.Data.DataSet();
    ap.Fill(ds, "Database");
    DataGridView1.DataSource = ds.Tables[0];
    DataGridView1.DisplayMember = "Math";
}



My Database has 7 rows, so that column "Math" has 7 values are {10, 5.5, 6, 7.5, 9, 8, 8.5}.
I use the query "SELECT * FROM Database".
After that, How can I get the value of Math column to an array or a variable?
Posted
Updated 24-Dec-15 21:04pm
v2
Comments
Tomas Takac 25-Dec-15 2:38am    
You need to show your code. Use Improve question to update your question.

Well, you already have it in a collection - the DataTable that you filled and used as the data source for the DataGridView - so I'd probably access the values from that.
Try this:
C#
DataTable dt = ds.Tables[0];
double[] mathValues = new double[dt.Rows.Count];
int index = 0;
foreach (DataRow row in dt.Rows)
   {
   mathValues[index++] = (double) row["Math"];
   }
 
Share this answer
 
C#
private void btn_info_Click(object sender, EventArgs e)
   
SqlConnection con;
SqlCommand cm1;
DataSet ds;
SqlDataAdapter ap;
 {
        cm1 = new SqlCommand("SELECT * FROM Database ", con);

        ap = new SqlDataAdapter(cm1);
        ap.Fill(ds);
        DataGridView1.DataSource = ds;
        DataGridView1.DataBind();
    }
 
Share this answer
 
v2

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