【问题标题】:Filling gridview from codebehind从代码隐藏填充gridview
【发布时间】:2014-09-09 20:25:02
【问题描述】:

我的 ASP.NET Web 表单中有一个 gridview 控件。我过去曾使用相同的代码在 Windows 窗体应用程序中使用数据填充网格视图。

这是我的代码:

var sql = new SQL_Statements();
var stringSql = "select col1, col2, col3, col4 from table1 where col5=" + stringPO_NUM;
var sql_ds = sql.SelectFromDB(stringSql);
int DataIndex;
if (sql_ds.Tables["CurData"].Rows.Count > 0)
    for (DataIndex = 0; DataIndex <= sql_ds.Tables["CurData"].Rows.Count - 1; DataIndex++)
    {
        sql_ds.Tables["CurData"].Rows[DataIndex]["col4"].ToString();
        //Fill the datagridview with the data that was just pulled from SQL_Statements
        GV_POI.DataSource = sql_ds;
        GV_POI.DataMember = "CurData";
    }

这是 SelectFromDB 的代码:

public DataSet SelectFromDB(String Sql)
        {
            var functionReturnValue = default(DataSet);
            var Class_Connection = new SQL_Connection();
            Class_Connection.cnn.Close(); //Let's close the connection, just in case it is open
            Class_Connection.cnn.Open();                
            var myDataAdaptor = new SqlDataAdapter(Sql, Class_Connection.cnn);
            var myDataset = new DataSet();

            try
            {
                myDataAdaptor.SelectCommand.Connection = Class_Connection.cnn;
                myDataAdaptor.SelectCommand.CommandText = Sql;
                myDataAdaptor.SelectCommand.CommandType = CommandType.Text;
                myDataAdaptor.Fill(myDataset, "CurData");
                functionReturnValue = myDataset;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Class_Connection.cnn.Close();
            }
            return functionReturnValue;
            Class_Connection.cnn.Close();
        }

这是 ASPX 页面中 GridView 的代码:

<asp:GridView ID="GV_POI" runat="server" AutoGenerateColumns="False">
                        </asp:GridView>

我不确定我做错了什么。当页面加载时,gridview 是空白的。我检查了调试器中的代码,并且代码正在触发。有人可以告诉我我做错了什么吗?

【问题讨论】:

  • col5 是字符类型还是数字类型?无论如何,您不应该使用参数来设置该值吗?
  • @rontornambe col5 是数字
  • 你检查过回发吗? if(!Page.IsPostBack) { CallBindFunction(); }
  • @HassanNisar No. 代码在 Page_LoadComplete 中触发,我在调试器中检查了
  • check @Lorin's 回答我认为你错过了GV_POI.DataBind();

标签: c# asp.net gridview webforms sqldatasource


【解决方案1】:

如果您要获取数据集“sql_ds”中的所有数据,则不需要 for 循环, 你可以这样做

GV_POI.DataSource = sql_ds.Tables[0];
GV_POI.DataBind();

并且要么使 AutoGenerateColumns="True" 要么使用 BoundField 或 TemplateField。

例子:

<asp:GridView ID="gvTest" runat="server" AutoGenerateColumns="False" GridLines="Vertical"
     OnRowEditing="gvTests_RowEditing"  AllowPaging="True" PageSize="20"
     OnRowDataBound="gvTest_RowDataBound">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-CssClass="hidecss" HeaderStyle-CssClass="hidecss" >
      <ItemStyle Width="80px" HorizontalAlign="Left" />
      <HeaderStyle Width="80px" Wrap="False" />
</asp:BoundField>                           
<asp:BoundField HeaderText="Name" DataField="Name">
      <ItemStyle Width="200px" HorizontalAlign="Left" />
      <HeaderStyle Width="200px" Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="Description" DataField="Description">
      <ItemStyle Width="200px" HorizontalAlign="Left" />
      <HeaderStyle Width="200px" Wrap="False" />
</asp:BoundField>                          
<asp:CommandField ShowEditButton="true" EditImageUrl="~/images/edit.png" ButtonType="Image">
      <HeaderStyle Width="20px" />
      <ItemStyle Width="20px" />
</asp:CommandField>
<asp:TemplateField>
    <ItemTemplate>
      <asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete"
      ImageUrl="~/images/delete.png" AlternateText="Delete"
      ToolTip="Click to Delete"></asp:ImageButton>
    </ItemTemplate>
    </asp:TemplateField>
</Columns>
    <HeaderStyle CssClass="HeaderCss" />
    <PagerStyle CssClass="PagerCss" />                        
    <AlternatingRowStyle CssClass="AltRowCss" />
    <EditRowStyle CssClass="EditRowCss" />
</asp:GridView>

【讨论】:

  • 我没有看到名为 BoundField 或 TemplateField 的属性
  • @nate 我已经用 BoundField、CommandField 和 TemplateField 的示例编辑了我的答案。
【解决方案2】:

在我看来,您正在将 GV_POI 绑定到一个字符串

var stringSql = "select col1, col2, col3, col4 from table1 where col5=" + stringPO_NUM;
GV_POI.DataSource = stringSql;

不是实际的数据列表。

我想你想要

GV_POI.DataSource = sql_ds;

【讨论】:

  • 这就是它的编码方式,它是打字机,对此感到抱歉。我编辑了问题
【解决方案3】:

在循环结束时不要忘记databind()

GV_POI.DataBind();

【讨论】:

  • 试过了,gridview还是空白
  • @nate 请显示SelectFromDB 它应该返回一个数据表
【解决方案4】:

您应该设置 DataSource 属性,然后绑定它。很好的例子可以在这里找到:http://msdn.microsoft.com/en-us/library/fkx0cy6d(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

  DataSet ds = GetData(queryString);
  if (ds.Tables.Count > 0)
  {
    AuthorsGridView.DataSource = ds;
    AuthorsGridView.DataBind();
  }

【讨论】:

  • 仍然无法解析符号 GetData 或 AuthorsGridView
【解决方案5】:

如果您尝试将GV_POI.DataBind() 附加到您的代码中,但没有成功,那么我将查看触发您的代码执行的事件。是页面加载事件吗?还要检查您是否有任何GV_POI 事件可能会覆盖您的数据绑定事件?例如GV_POI_DataBoundGV_POI_RowDataBound?

【讨论】:

    【解决方案6】:

    你去吧:

        public DataTable SelectFromDB(String Sql)
        {
    
            var Class_Connection = new SQL_Connection();
    
            Class_Connection.cnn.Open();                
            var myDataAdaptor = new SqlDataAdapter(Sql, Class_Connection.cnn);
            var myDataTable = new DataTable();
    
            try
            {
                myDataAdaptor.SelectCommand.Connection = Class_Connection.cnn;
                myDataAdaptor.SelectCommand.CommandText = Sql;
                myDataAdaptor.SelectCommand.CommandType = CommandType.Text;
                myDataAdaptor.Fill(myDataTable);
                Class_Connection.cnn.Close(); 
                return myDataTable;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Class_Connection.cnn.Close();
                return null;
            }
        }
    
    
    var sql = new SQL_Statements();
    var stringSql = "select col1, col2, col3, col4 from table1 where col5=" + stringPO_NUM;
    var sql_ds = sql.SelectFromDB(stringSql);
    
    GV_POI.DataSource = sql_ds;
    GV_POI.DAtaBind();
    
    
    <asp:GridView ID="GV_POI" runat="server" AutoGenerateColumns="False">
        <EmptyDataTemplate>No records registered</EmptyDataTemplate>
    </asp:GridView>`
    

    【讨论】:

      【解决方案7】:

      试试这个

      在 DataTable 中获取您的数据,然后

      if (dt.Rows.Count > 0)
      {
          grid.DataSource = dt;
          gridDataBind();
      }
      

      【讨论】:

        【解决方案8】:

        我认为您需要在当前设置数据成员的地方执行以下操作,因为您当前似乎没有将数据绑定到数据网格:

        string member;
        member = "CurData";
        GV_POI.SetDataBinding(sql_ds, member);
        

        编辑 - 以下更新:

        如果您将“AutoGenerateColumns”设置为“false”,则需要指定列。一个例子是:

        <Columns>
            <asp:TemplateColumn>
                <HeaderTemplate>Job Number</HeaderTemplate>
                <ItemTemplate><%# Eval("Job Number") %></ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
        

        显然,您可能只想简单地做一个 'BoundColumn' 或类似的东西。您还需要替换您自己的标题数据等。您需要对基本上要显示的每一列执行此操作。或者,只需将“AutoGenerateColumns”设置为“true”。

        【讨论】:

        • 好的,既然您在数据集中只返回 1 个数据表,那么您可以使用 GV_POI.DataBind()。
        • 我只是在循环结束时尝试过。网格视图仍然是空白的
        • @nate 我看到你为此标记了答案。在标记答案之前,您是否在我的编辑中尝试了我的建议?
        • 我现在正在查看@您的编辑。为了回答您的问题,不,因为 gmd 在您编辑前几个小时回答了问题。
        • @nate 感谢您查看我的编辑。很高兴知道问题是什么。至于答案的时间安排,我的编辑是在 23 小时前(发表此评论时)完成的,而标记的答案是在 21 小时前完成的......
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 2011-04-09
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        相关资源
        最近更新 更多