我有一个带有复选框字段和几个绑定(bind)字段的 gridview 控件。复选框字段不直接映射到数据库中的字段。相反,我想从数据库中的一个字段中读取一个值并“选中”一些复选框。
例如,从数据库->数据表中给出以下数据
PROCESSED NAME DATE Y Mickey Mouse 11/15/2011 N Donald Duck 4/01/2012 Y James Bond 5/02/2011
I would like the gridview to display a checkbox and set the value of boxes to UNCHECKED where PROCESSED = N and for PROCESSED = Y either have an uneditable checkbox or no checkbox at all.
PROCESSED NAME DATE [/] Mickey Mouse 11/15/2011 [ ] Donald Duck 4/01/2012 [/] James Bond 5/02/2011
To populate the gridview, a SQL stmt is run against a database, and the result of the SQL query is stored in a datatable. Before binding the datatable to the gridview, i would like to check the "processed" field and set the checkbox based on that value.
Here is the gridview control (shortened for clarity):
<asp:GridView ID="gridview_all_applicants" runat="server" AllowPaging="True">
<Columns>
<asp:TemplateField HeaderText="Complete">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="lastname" HeaderText="Last Name" ReadOnly="True" SortExpression="lastname" />
这是我到目前为止在后面的代码中的内容
SqlCommand cmd = new SqlCommand(sql query here);
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
// do some processing of data returned from query
// read the char value from the returned data and set checkbox
procflag = r["process_flag"].ToString().ToLower();
CheckBox chkbox = new CheckBox();
if (procflag == null || procflag == "n")
{
// SET CHECKBOX TO "NOT CHECKED"
}
else
{
// SET CHECKBOX TO "CHECKED" AND MAKE IT UNCLICKABLE
// ----OR---- DO NOT DISPLAY CHECKBOX AT ALL.
}
} // end for each
gridview_all_applicants.DataSource = dt;
gridview_all_applicants.DataBind();
非常感谢任何帮助。
最佳答案
你可以这样做:
首先在sql server中:
SELECT
CAST(CASE PROCESSED WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED
NAME
DATE
FROM ExampleTable
在 C# 代码中:
SqlCommand cmd = new SqlCommand(sql query here);
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
gridview_all_applicants.DataSource = dt;
gridview_all_applicants.DataBind();
最后在 aspx 中:
<asp:TemplateField HeaderText="Complete">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server" Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>' Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'/>
</ItemTemplate>
关于c# - 根据数据表值在gridview中设置复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6445178/