【发布时间】:2014-08-26 12:22:47
【问题描述】:
c#中如何从DataTable中获取特定列的值
我的代码 C# 有问题。
我需要从 DataTable 中读取特定的列值。
我尝试使用此解决方案没有成功,因为输出是查询中选择的列的名称 (File) 而不是字段数据库的值。
非常感谢您在解决这个问题时给我的任何帮助。
这是我的代码:
public DataTable GridViewBind()
{
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";
using (OdbcDataAdapter command =
new OdbcDataAdapter(sql1, cn))
{
try
{
cn.Open();
dset = new DataSet();
dset.Clear();
command.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Write(dt.Columns[0].ToString());
return dt;
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
if (command != null)
{
command.Dispose();
}
if (cn != null)
{
cn.Close();
cn.Dispose();
}
}
}
}
}
编辑#1
现在我有错误:
System.IndexOutOfRangeException:位置 0 处没有行。
public DataTable GridViewBind()
{
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";
using (OdbcDataAdapter command =
new OdbcDataAdapter(sql1, cn))
{
try
{
cn.Open();
dset = new DataSet();
dset.Clear();
command.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
string file = dt.Rows[0].Field<string>(0);
Response.Write(file.ToString());
return dt;
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
if (command != null)
{
command.Dispose();
}
if (cn != null)
{
cn.Close();
cn.Dispose();
}
}
}
}
}
【问题讨论】:
-
问题不清楚。是什么使哪一列的值具体?该表通常包含多行。使用循环并使用
row.Field<string>(0)访问每一行的值。 -
我需要读取在查询 sql1 中选择的列 File 的值。
-
也许有帮助: if ( dt.Columns[ 0 ].ColumnName == "columnName" ) { gridview1.DataSource = dt; gridview1.DataBind(); }