[英]How do I make items in the ListBox as headers of GridView
我有一個ListBox
,on_button單擊,我希望ListBox
中的所有項目在GridView
顯示為標題。 這是我嘗試過的代碼:
protected void DONE4_Click(object sender, EventArgs e)
{
Panel7.Visible = true;
DataTable dt = new DataTable();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
dt.Columns.Add(ListBox1.Items[i].ToString());
}
GridView2.DataSource = dt;
GridView2.DataBind();
foreach (GridViewRow grdRow in GridView2.Rows)
{
DropDownList bind_dropdownlist = new DropDownList(); // defining the property of the DropDownList as bind_dropdownlist
bind_dropdownlist = (DropDownList)(GridView2.Rows[grdRow.RowIndex].Cells[0].FindControl("Pro_List")); // finding the DropDownList from the gridiew for binding
SqlDataAdapter mydata = new SqlDataAdapter("SELECT DISTINCT Profile_Instance FROM Profile_Master", con);
DataSet dset = new DataSet(); // binding the DropDownList with the dataset ds
mydata.Fill(dset, "Table");
bind_dropdownlist.DataSource = dset;
bind_dropdownlist.DataTextField = "Profile_Instance"; // set the DropDownList's DataTextField as designation which display the designation in the dropdownlist after fetching the data from database
bind_dropdownlist.DataBind();
bind_dropdownlist.Items.Insert(0, new ListItem("---Choose Profile---", "-1"));
}
}
我希望ListBox
中的所有項目都顯示為GridView
標題字段。
上面的代碼沒有錯誤,但運行時它不起作用。 有人可以幫我這個嗎?
這是GridView
設計代碼:
<asp:Panel ID="Panel7" runat="server">
<asp:GridView ID="GridView2" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" style="text-align: center; font-size: small">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="Pro_List" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
設置DataSource后,調用DataBind
方法並查看會發生什么
GridView2.DataSource = dt;
GridView2.DataBind();
編輯:以下代碼工作得很好。 測試。
如果Grid中沒有數據,除非為網格提供EmptyText字段屬性值,否則它甚至不顯示任何標題。
DataTable dt = new DataTable();
DataRow rw = default(DataRow);
for (int i = 0; i < ListBox1.Items.Count; i++)
{
dt.Columns.Add(ListBox1.Items[i].ToString(),
System.Type.GetType("System.String"));
}
//Simply adding 10 rows
//Replace this hard coded loop with your looping
// over your data to add rows.
for (int j = 0; j < 10; j++)
{
rw = dt.NewRow();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
rw[ListBox1.Items[i].ToString()] = "Hello there";
}
dt.Rows.Add(rw);
}
GridView1.DataSource = dt;
GridView1.DataBind();
該鏈接提供了工作樣本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.