我的网格视图在第一列中有复选框。单击复选框时,我想禁用该行,但保持启用复选框。
此代码禁用整行,包括复选框:
protected void chkRow_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkRow = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkRow.NamingContainer;
if (chkRow.Checked)
{
// Enable the row
row.Enabled = false;
row.Style["background-color"] = "#F5F5F5";
chkRow.Enabled = true;
}
else
{
// ....
}
}
好的,所以说这个标记:
<asp:GridView ID="GVHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table table-hover"
width="50%">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate >
<asp:CheckBox ID="chkRow" runat="server"
OnCheckedChanged="chkRow_CheckedChanged"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txtDesc" runat="server"
TextMode="MultiLine" Rows="4" Width="100%"
Text='<%# Eval("Description") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
加载后面的代码,并处理复选框:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
string strSQL =
@"SELECT * FROM tblHotelsA
WHERE Description is not null
AND Active = 1
ORDER BY HotelName";
GVHotels.DataSource = General.MyRst(strSQL);
GVHotels.DataBind();
}
protected void chkRow_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkRow = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkRow.NamingContainer;
if (chkRow.Checked)
row.Style["background-color"] = "skyblue"; // color row for checked box
else
row.Style["background-color"] = "white"; // color row for un-checked box
// now disable all controls in row EXACPT for first cell (checkbox)
for (int i=1;i < row.Cells.Count;i++)
row.Cells[i].Enabled = !chkRow.Checked;
}
因此,我们只需禁用(或启用)该给定行中的所有单元格,跳过包含复选框控件的第一个单元格,即可代替“整”行禁用。
结果是这样的: