[英]How to add gridview controls dynamically when retrieve values from database?
我想检索值并将其绑定到数据库的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++;
}
}
有任何想法吗? 提前致谢
我想检索值并将其绑定到数据库的gridview中
您可以从存储库/ DAL中填充数据,并在页面Load事件内将gridview绑定到数据。 您完全不必使用row 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();
}
您可以在gridview内为文本框添加模板字段。 您将为每个文本框指定dataTable列的名称,以便它自动获取数据绑定。
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="myTextBox" runat="sever" Text='<%#Bind("YourDataTableColumnName") %>' ></asp:TextBox>
</ItemTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.