【发布时间】:2017-06-20 00:33:09
【问题描述】:
我不断收到以下“System.ArgumentException”错误,内容为
DataBinding:“System.Data.DataTable”不允许索引访问。
在我的 GridView 中。当我运行项目时,它会进入 html 标签<asp:Label ID="lblTargetName" runat="server" Text='<%# Eval("[TargetName]") %>'></asp:Label>
这是 HTML:
<asp:GridView>
<asp:TemplateField HeaderText="TargetName" SortExpression="TargetName">
<ItemTemplate>
<asp:Label ID="lblTargetName" runat="server" Text='<%# Eval("[TargetName]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
以及后面绑定网格的代码:
protected void UpdateGridview()
{
string PlanningType = DropDownList4.SelectedValue.ToString();
string ProductionYear = null;
//SqlDataSource sds = new SqlDataSource();
SqlConnection con = new SqlConnection(DatabaseConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
//sds = Page.FindControl("SqlDataSource1") as SqlDataSource;
if (DropDownList5.SelectedValue != "")
ProductionYear = DropDownList5.SelectedValue.ToString();
try
{
if (ProductionYear != null)
{
using (con)
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_GetSUPPExcelImport", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@PlanningType", SqlDbType.VarChar));
cmd.Parameters["@PlanningType"].Value = PlanningType.ToString();
cmd.Parameters.Add(new SqlParameter("@ProductionYear", SqlDbType.VarChar));
cmd.Parameters["@ProductionYear"].Value = ProductionYear;
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables;
GridView1.AllowPaging = true;
GridView1.DataBind();
}
}
}
catch (Exception ex)
{
Label1.ForeColor = Color.Red;
Label1.Text = ex.Message.ToString();
}
finally
{
if (da != null)
da.Dispose();
if (ds != null)
ds.Dispose();
if (con != null)
{
con.Close();
con.Dispose();
}
}
【问题讨论】:
-
您正在将一组数据表分配给 gridview 数据源。那是行不通的。您需要从数据集中分配其中一个表,例如
GridView1.DataSource = ds.Tables[0];。之后,您还应该从 eval 中删除[和]:Text=''。如果它仍然不起作用,您应该告诉我们更多关于存储过程返回的内容。 -
感谢您的帮助。
标签: c# asp.net gridview data-binding visual-studio-2015