我试图将我从数据库中检索到的数据显示为我动态创建的表..但我得到错误。请帮助解决 [英] I Tried To Display The Data That I Retrieved From Database To Table That I Created Dynamically.. But I Am Getting error .Please Help To Solve
本文介绍了我试图将我从数据库中检索到的数据显示为我动态创建的表..但我得到错误。请帮助解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
protected void Button1_Click(object sender, EventArgs e)
{
makedatatable();
}
private void makedatatable()
{
DataTable dt = new DataTable("mytable");
DataColumn col = new DataColumn();
col = new DataColumn("sid");
dt.Columns.Add(col);
col = new DataColumn("sname");
dt.Columns.Add(col);
col = new DataColumn("dname");
dt.Columns.Add(col);
col = new DataColumn("date");
dt.Columns.Add(col);
col = new DataColumn("status");
dt.Columns.Add(col);
DataRow row;
DataSet obj = staffdata.getattdstatus();
if (obj.Tables[0].Rows.Count != 0)
{
for (int i = 0; i < obj.Tables[0].Rows.Count; i++)
{
String stid = obj.Tables[0].Rows[i]["StaffId"].ToString();
row["sid"] = stid;
dt.Rows.Add(row);
String sname = obj.Tables[0].Rows[i]["Staffname"].ToString();
row["sname"] = sname;
dt.Rows.Add(row);
String dname = obj.Tables[0].Rows[i]["Deptname"].ToString();
row["dname"] = dname;
dt.Rows.Add(row);
String d = obj.Tables[0].Rows[i]["Date"].ToString();
row["date"] = d;
dt.Rows.Add(row);
String st = obj.Tables[0].Rows[i]["Status"].ToString();
row["status"] = st;
dt.Rows.Add(row);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
推荐答案
为什么所有这些代码!
更改aspx page Gridview标记绑定特定列如下所示
why all these code!
change the aspx page Gridview markup to bind the specific columns as below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="StaffId" HeaderText="sid" />
<asp:BoundField DataField="Staffname" HeaderText="sname" />
<asp:BoundField DataField="Deptname" HeaderText="dname" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Status" HeaderText="status" />
</Columns>
</asp:GridView>
然后你可以改变如下方法
then you can change the method as below
private void makedatatable()
{
DataSet obj = staffdata.getattdstatus();
if(obj !=null && obj.Tables.Count >0)
{
GridView1.DataSource = obj.Tables[0];
GridView1.DataBind();
}
}
DataRow row=dt.NewRow();
if u do like this then u dont need to add columns to row like row["sid"]
simply assign the values to this row like row[0]="abc";
then finally dt.Rows.Add(row);
DamithSL是正确的。
顺便提一下,请尝试使用此代码。这只是为了你的理解。记住
DamithSL is correct.
By the way for error, try this code. this is just for your understanding. remember variables in
dt.Rows.Add()
中的变量必须与列中的列相同。
$ / b
must be in same sequence as columns are in table.
for (int i = 0; i < obj.Tables[0].Rows.Count; i++)
{
String stid = "id" + i;
String sname = "Sname" + i;
String dname = "Dname" + i;
String d = "D" + i;
String st = "St" + i;
dt.Rows.Add(stid,sname,dname,d,st);
}
这篇关于我试图将我从数据库中检索到的数据显示为我动态创建的表..但我得到错误。请帮助解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文