【问题标题】:How to add gridview controls dynamically when retrieve values from database?从数据库中检索值时如何动态添加gridview控件?
【发布时间】:2013-10-22 08:47:53
【问题描述】:

我想从数据库中检索值并将其绑定到 gridview 中

根据我想动态添加控件的行数

代码:

在我的表格中我有 2 行,但使用下面的代码我只能得到第二行的值

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    int rowIndex = 0;
    OleDbCommand cmd = new OleDbCommand("select activities,monday,tuesday,wednesday,thursday,friday,saturday,sunday from activity_values where week = '" + weekNumNow + "' and emp_id = (select emp_id from emp_master where username = '" + username + "')", DbConnection);
    // DbConnection.Open();
    OleDbDataReader dr1 = cmd.ExecuteReader();
    while (dr1.Read())
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //find the control
            DropDownList drop1 = e.Row.FindControl("dropActivities") as DropDownList;
            TextBox box1 = e.Row.FindControl("TextBox1") as TextBox;
            TextBox box2 = e.Row.FindControl("TextBox2") as TextBox;
            TextBox box3 = e.Row.FindControl("TextBox3") as TextBox;
            TextBox box4 = e.Row.FindControl("TextBox4") as TextBox;
            TextBox box5 = e.Row.FindControl("TextBox5") as TextBox;
            TextBox box6 = e.Row.FindControl("TextBox6") as TextBox;
            TextBox box7 = e.Row.FindControl("TextBox7") as TextBox;

            drop1.Text = dr1[0].ToString();
            box1.Text = dr1[1].ToString();
            box2.Text = dr1[2].ToString();
            box3.Text = dr1[3].ToString();
            box4.Text = dr1[4].ToString();
            box5.Text = dr1[5].ToString();
            box6.Text = dr1[6].ToString();
            box7.Text = dr1[7].ToString();
        }
        rowIndex++;
    }
}

有什么想法吗?提前致谢

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    我想从数据库中检索值并将其绑定到 gridview 中

    您可以从您的存储库/DAL 中填充数据并在页面加载事件中绑定您的网格视图。您根本不必使用行 DataBound 事件,因为这将为呈现的每一行打开一个数据库连接。我认为您只看到一行,因为它是数据库返回的最后一行。一些伪代码

    PageLoad()
    {
       if(!Page.IsPostBack)
       { 
         PopulateMyGrid();
       }
    }
    
    private void PopulateMyGrid()
    {
        DataTable myDataTable=null;
        // Your DAL code goes here (you can fill the datatable from your database)
        myGrid.DataSource = myDatatable;
        myGrid.DataBind();
    }
    

    您可以在网格视图中为文本框添加模板字段。对于每个文本框,您将指定 dataTable 列的名称,以便它自动进行数据绑定。

    <asp:TemplateField>
      <ItemTemplate>
        <asp:TextBox ID="myTextBox" runat="sever" Text='<%#Bind("YourDataTableColumnName") %>' ></asp:TextBox>   
    </ItemTemplate>
    

    【讨论】:

    • 感谢您的回复..我知道这段代码应该可以正常工作,但如果我在数据库表中没有任何值,那么这里 Text=' 我们会出错吗?那么如何解决呢?
    • @user2500094 你不会得到任何错误。你试过什么?
    • 查看这个链接 geekswithblogs.net/dotNETvinz/archive/2009/08/02/… 我实现了这个,我想通过我们添加的同一个 gridview 读取这些值
    • 请帮助我如何检索这些值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多