What is the easiest way to export the items from 开发者_JS百科an asp:listbox
into a dataset?
This is a fairly straight forward way that should work regardless of how you populate it, can't think of a faster way...
public static DataTable GetListBoxItems(ListBox listBox)
{
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Text");
dt.Columns.Add("Selected");
dt.Columns.Add("Attributes");
foreach (ListItem itm in listBox.Items)
{
DataRow dr = dt.NewRow();
dr[0] = itm.Value;
dr[1] = itm.Text;
dr[2] = itm.Selected;
dr[3] = itm.Attributes;
dt.Rows.Add(dr);
}
return dt;
}
OR with extension method:
public static class Extensions
{
public static DataTable GetListBoxItems(this ListBox listBox)
{
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Text");
dt.Columns.Add("Selected");
dt.Columns.Add("Attributes");
foreach (ListItem itm in listBox.Items)
{
DataRow dr = dt.NewRow();
dr[0] = itm.Value;
dr[1] = itm.Text;
dr[2] = itm.Selected;
dr[3] = itm.Attributes;
dt.Rows.Add(dr);
}
return dt;
}
}
Then you can call it like this:
ListBox1.GetListBoxItems();
精彩评论