如何从c#中的DataTable获取特定列值
我的代码C#有问题.
我需要从DataTable中读取特定的列值.
我尝试使用此解决方案但没有成功,因为输出是在查询(文件)中选择的列的名称,而不是字段数据库的值.
我非常感谢您在解决这个问题时能给我的任何帮助.
这是我的代码:
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();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑#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();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该表通常包含多行.使用循环并使用row.Field<string>(0)来访问每行的值.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
Run Code Online (Sandbox Code Playgroud)
您也可以通过索引访问它:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
Run Code Online (Sandbox Code Playgroud)
如果您只期望一行,您还可以使用以下索引器DataRowCollection:
string file = dt.Rows[0].Field<string>(0);
Run Code Online (Sandbox Code Playgroud)
如果表为空,则失败,请使用dt.Rows.Count以检查是否存在行:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
Run Code Online (Sandbox Code Playgroud)