我点击了一个按钮,我想显示gridview
之前它曾经基于Datatable
但现在我想在Array
这是代码
protected void btnSubmit_Click(object sender, EventArgs e)
{
var selectedItems = cmbEmp_Name.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value).ToArray();
var result = String.Join(",", selectedItems);
string[] StrAreaInt = result.Split(new char[] { ',' });
for (int i = 0; i < StrAreaInt.Length; i++)
{
Muster_Process(StrAreaInt[i]); // length comes here
HiddenDiv.Visible = true;
grdMonthlyProc.Visible = true;
}
}
答案 0 :(得分:1)
这些是我认为您正在使用的控件。
<asp:CheckBoxList ID="cmbEmp_Name" runat="server" RepeatLayout="Flow"></asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:GridView ID="grdMonthlyProc" runat="server" AutoGenerateColumns="true"></asp:GridView>
确保仅为DataSource分配一次,否则您将在每个Postback上丢失所选项目。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Changes these to your field names
cmbEmp_Name.DataTextField= "Name";
cmbEmp_Name.DataValueField = "DoctorID";
// This code populate the CheckBoxList in my own project
// Your Post doesn't show how you populate your control
// I assume it's being done elsewhere in your code.
// But it is important to understand that if you do not load
// the CheckBoxList within a `if (!Page.IsPostBack)` block anything
// you select in the list will be lost when you click the button
// because the control will be repopulated on Postback.
cmbEmp_Name.DataSource = ef6Context.GetListOfNames().ToList();
cmbEmp_Name.DataBind();
}
}
//Button1 Postback bind the Gridview.
protected void Button1_Click(object sender, EventArgs e)
{
// Once you select a number of items from `cmbEmp_Name` and hit your
// button this statement will create and Array of `ListItem`s
grdMonthlyProc.DataSource = cmbEmp_Name.Items
.Cast<ListItem>()
.Where(li => li.Selected)
.ToArray();
// And this will Bind the Array to the GridView. Internally GridView
// will extract all Public Properties of a ListItem and automatically
// generate a default set of Columns to display. With a simple
// redefinition you can display specific columns, but more on that later
grdMonthlyProc.DataBind();
}
你帖子中的代码块做了太多工作:
Value
Value
Value
然后你有一个for循环。我不知道为什么,但你调用Muster_Process我认为是相关的,但你没有说它是做什么的。并且您重复将可见性设置为循环内的相同控件(HiddenDiv
和grdMonthlyProc
),这没有用处。一旦在循环之外就足够了。
但是在帖子的第一行,你提到要填充GridView,但是你没有说出你想要显示的内容。
定义如下grdMonthlyProc
将显示ListItems的所有公共属性:
<asp:GridView ID="grdMonthlyProc" runat="server" AutoGenerateColumns="true">
</asp:GridView>
重新定义到此(请注意此更改:AutoGenerateColumns="false"
)这将仅显示值属性:
<asp:GridView ID="grdMonthlyProc" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
添加额外的BoundField
只会显示“值”字段和“文本字段”:
<asp:GridView ID="grdMonthlyProc" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Value" HeaderText="Value" />
<asp:BoundField DataField="Text" HeaderText="Text" />
</Columns>
</asp:GridView>