将复选框列插入datagridview时,我使用以下代码,
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Add(checkBoxColumn);
当我尝试选择复选框时,它不是 selectecd (未选中或未选中),有没有更好的方法来做到这一点?
将复选框列插入datagridview时,我使用以下代码,
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Add(checkBoxColumn);
当我尝试选择复选框时,它不是 selectecd (未选中或未选中),有没有更好的方法来做到这一点?
你可以用这篇文章
rotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Check for the row type, which should be data row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the check boxes and assign the values from the data source
((CheckBox)e.Row.FindControl("chkSelect")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[1]);
((CheckBox)e.Row.FindControl("chkAdd")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[2]);
((CheckBox)e.Row.FindControl("chkEdit")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[3]);
((CheckBox)e.Row.FindControl("chkAll")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[4]);
//Find the checkboxes and assign the javascript function which should
//be called when the user clicks the checkboxes.
((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onclick", "checkBoxClicked('" +
((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID
+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'SELECT')");
((CheckBox)e.Row.FindControl("chkAdd")).Attributes.Add("onclick", "checkBoxClicked('" +
((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID
+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'ADD')");
((CheckBox)e.Row.FindControl("chkEdit")).Attributes.Add("onclick", "checkBoxClicked('" +
((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID
+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'EDIT')");
((CheckBox)e.Row.FindControl("chkAll")).Attributes.Add("onclick", "checkBoxClicked('" +
((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID
+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'ALL')");
}
}
您只是在 gridview 中添加一列,但在为 gridview 分配数据源时。将 gridview 与数据源绑定以访问行以选中或取消选中复选框。
根据评论进行编辑。
您可以使用 RowDataBound 事件在 bihnding 期间使用带有数据源数据的网格视图的行实例来启用/禁用复选框。
void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = (CheckBox)e.Row.FindControl("chkBoxID");
if(DataBinder.Eval(e.Row.DataItem, "datasourceColumnName").ToString() == "someval")
chk.Enabled = false;
}
}