C# 如何在c中用字符串变量存储数据表值#

C# 如何在c中用字符串变量存储数据表值#,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我已将表值存储在datatable中,我想将每个值存储在字符串变量中 using (SqlConnection con = new SqlConnection(connection)) { using (SqlCommand cmd = new SqlCommand("select top 1 * from tbl_invoice order by id desc", con)) { if (con.State != System.Data.Conne

我已将表值存储在datatable中,我想将每个值存储在字符串变量中

using (SqlConnection con = new SqlConnection(connection))
{      
    using (SqlCommand cmd = new SqlCommand("select top 1 * from tbl_invoice order by id desc", con))
    {
        if (con.State != System.Data.ConnectionState.Open)
        {
            con.Open();
        }
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        gvInvoice.DataSource = dt;
        gvInvoice.DataBind();
        gvInvoice.DataSource = dt;
        gvInvoice.DataBind();
        InvoiceNo = dt.TableName[0].ToString();
    }
}
您可以这样尝试:

var myString = dt.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
foreach(DataRow row in dt.Rows)
{ 
    string mtstr1 = row["col1"].ToString();
    string mtstr2 = row["col2"].ToString();
    string mtstr3 = row["col3"].ToString();   
}
如果你不想要数组,那么简单

string myString =dt.Rows[0][1].ToString();
编辑:

要按列名提取,可以尝试以下操作:

var myString = dt.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
foreach(DataRow row in dt.Rows)
{ 
    string mtstr1 = row["col1"].ToString();
    string mtstr2 = row["col2"].ToString();
    string mtstr3 = row["col3"].ToString();   
}

您可以使用Genericscan我们可以通过表的列名提取值。因为索引很混乱。与dt.rows[0].[invoiceno].tostring()类似@克:更新了我的答案!