如何从Database列获取值到变量 [英] How to get value from column of Database to variable

查看:115
本文介绍了如何从Database列获取值到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库有3列是名称,数学,化学和总和。我可以在C#中通过SQL查询某些行,但我不知道如何在C#中将值从列变为变量。如果有人知道,请帮助我!



例如:



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

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

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







我的数据库有7行,因此Math列有7行值为{10,5.5,6,7.5,9,8,8.5}。

我使用查询SELECT * FROM Database。

之后,我怎样才能将Math列的值变为数组或变量?

解决方案

嗯,你已经拥有了它在一个集合中 - 你填充并用作DataGridView的数据源的DataTable - 所以我可能会从中访问这些值。

试试这个:

< pre lang =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 ];
}


  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();
}


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:

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?

解决方案

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:

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"];
   }


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();
    }


这篇关于如何从Database列获取值到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆