如何更改如下代码,根据数据表的值列自动改变???
现在问题是:完全不知道数据表结构的情况下绑定数据..不知道有多少列,表头是什么???下面代码是在知道数据表结构的情况下编写,完全不知道数据表结构的情况下应该如何修改啊???十分感谢各位大哥代码:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection conn=new SqlConnection("server=.;database=northwind;uid=sa;pwd=aico");
conn.Open();
SqlCommand cmd=new SqlCommand("select CategoryID,CategoryName,Description from Categories",conn);
SqlDataAdapter sda=new SqlDataAdapter();
sda.SelectCommand=cmd;
DataSet ds=new DataSet();
Repeater1.HeaderTemplate = new MyTemplate(ListItemType.Header);
Repeater1.ItemTemplate = new MyTemplate(ListItemType.Item);
Repeater1.AlternatingItemTemplate =new MyTemplate(ListItemType.AlternatingItem);
Repeater1.FooterTemplate = new MyTemplate(ListItemType.Footer);
sda.Fill(ds,"Categories");
Repeater1.DataSource=ds.Tables["Categories"];
Repeater1.DataBind();
// 在此处放置用户代码以初始化页面
}
public class MyTemplate : System.Web.UI.ITemplate
{
System.Web.UI.WebControls.ListItemType templateType;
public MyTemplate(System.Web.UI.WebControls.ListItemType type)
{
templateType = type;
}
public void InstantiateIn(System.Web.UI.Control container)
{
PlaceHolder ph = new PlaceHolder();
Label item1 = new Label();
TextBox item2 = new TextBox();
TextBox item3 =new TextBox();
item1.ID = "item1";
item2.ID = "item2";
item3.ID="item3";
switch (templateType)
{
case ListItemType.Header:
ph.Controls.Add(new LiteralControl("<table border=\"1\">" +
"<tr><td><b>Category ID</b></td>" +
"<td><b>Category Name</b></td>"+"<td><b>Description</b></td></tr>"));
break;
case ListItemType.Item:
ph.Controls.Add(new LiteralControl("<tr><td>"));
ph.Controls.Add(item1);
ph.Controls.Add(new LiteralControl("</td><td>"));
ph.Controls.Add(item2);
ph.Controls.Add(new LiteralControl("</td><td>"));
ph.Controls.Add(item3);
ph.Controls.Add(new LiteralControl("</td></tr>"));
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.AlternatingItem:
ph.Controls.Add(new LiteralControl("<tr bgcolor=\"lightblue\"><td>"));
ph.Controls.Add(item1);
ph.Controls.Add(new LiteralControl("</td><td>"));
ph.Controls.Add(item2);
ph.Controls.Add(new LiteralControl("</td><td>"));
ph.Controls.Add(item3);
ph.Controls.Add(new LiteralControl("</td></tr>"));
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.Footer:
ph.Controls.Add(new LiteralControl("</table>"));
break;
}
container.Controls.Add(ph);
}
}
static void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
string item3Value=(string)DataBinder.Eval(ri.DataItem,"Description");
((Label)ph.FindControl("item1")).Text = item1Value.ToString();
((TextBox)ph.FindControl("item2")).Text = item2Value;
((TextBox)ph.FindControl("item3")).Text=item3Value;
}
补充:.NET技术 , ASP.NET