我在ASP.Net中设置了一个gridview,它有一个名称和一个复选框。
<h4>Current Instructor</h4>
<div class="hide-overflow">
<asp:GridView runat="server" ID="GridViewInstructor" DataSourceID="SqlDataSourceInstructor" AutoGenerateColumns="false" CssClass="table table-bordered table-striped" ShowHeader="false" EmptyDataText="No Instructor associated to class." DataKeyNames="Instructor">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CBInstructorPrimary" runat="server" Checked='<%#Eval("Primary")%>' OnCheckedChanged="PrimaryUpdate" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="InstructorName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSourceInstructor" DataSourceMode="DataReader" ConnectionString="<%$ ConnectionStrings:HRAgriConnectionString %>"
SelectCommand="
SELECT a.Primary, a.ClassID, a.Instructor, b.LName + ', ' + b.FName as InstructorName
FROM tblClass a
LEFT JOIN tblUser b
ON a.Instructor = b.UserName
WHERE a.ClassID = @classID
ORDER BY a.Primary DESC">
<SelectParameters>
<asp:QueryStringParameter Name="classID" QueryStringField="cid" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
这使得gridview表看起来像
我的c#代码背后看起来像这样
protected void PrimaryUpdate(object sender, EventArgs e)
{
//CheckBox activeCheckBox = sender as CheckBox;
//foreach (GridViewRow rw in GridViewInstructor.Rows)
//{
// CheckBox chkBx = (CheckBox)rw.FindControl("CBInstructorPrimary");
// if (chkBx != activeCheckBox)
// {
// chkBx.Checked = false;
// }
// else
// {
// chkBx.Checked = true;
// }
//}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE tblClass SET [Primary] = @Primary WHERE classID=@classID and Instructor = @InstructorName";
cmd.Connection = con;
con.Open();
foreach (GridViewRow row in GridViewInstructor.Rows)
{
//Get Instructor Name.
string InstructorName = row.Cells[0].Text;
//Get the Class Id from the DataKey property.
classID = Request.QueryString["cid"];
//Get the checked value of the CheckBox.
bool Primary = (row.FindControl("CBInstructorPrimary") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@InstructorName", InstructorName);
cmd.Parameters.AddWithValue("@classID", classID);
cmd.Parameters.AddWithValue("@Primary", Primary);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
结果应该是如果你选中另一个复选框,它会将主要字段(这是一个位字段)更新为1(如果选中),并且该组中的所有其他复选框都将设置为0.并且只能选中一个复选框。时间。我知道我现在已经评论了最重要的部分。我还没有能够弄清楚如何使这个工作。