C#.net GridView.DataSource

时间:2016-11-02 17:01:28

标签: c# asp.net gridview

在.aspx我有

<body>
  <form id="form2" runat="server">
 <asp:GridView ID="GridView" runat="server" AutoGenerateColumns="True" Width="100%" ViewStateMode="Enabled">
 <Columns>
    <asp:BoundField ItemStyle-Width="150px" DataField="id" HeaderText="iD" />
    <asp:BoundField ItemStyle-Width="150px" DataField="nme" HeaderText="Name" />
    </Columns>
</asp:GridView>
   </form>
</body>

在.cs中我有

private void Grid()
{
    string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT id, nme FROM mytable"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView.DataSource = dt; //error occurs here
                    GridView.DataBind();
                }
            }
        }
    }
}

我收到错误 CS0120非静态字段,方法或属性需要对象引用&quot; BaseDataBoundControl.DataSource&#39;

.cs似乎无法识别.aspx页面中的GridView。 使用.net 4.6.1

1 个答案:

答案 0 :(得分:3)

请勿调用GridView&#34; GridView&#34;。该框架不知道您是否正在谈论您的GridView实例,或者您是否正在谈论类GridView。这令人困惑,难以讨论,而且令编译器感到困惑。将ID更改为与预先存在的类型名称不冲突的其他内容,并相应地更新您的代码。您通常在它包含的内容之后命名,ex CustomersGridView

标记

<asp:GridView ID="CustomersGridView" runat="server">

背后的代码

CustomersGridView.DataSource = dt;
CustomersGridView.DataBind();