我是c#编码的新手,我对此很感兴趣。
我有一个带有DataGridViewCheckBoxColumn列的DataGridView,它被数据绑定到一个列表。
将过滤器应用到datagridview后,过滤器工作正常,但是如果我使用复选框检查行,我就不能保留它,因为点击后面我再次加载datagridview,这会导致复选框选择也会再次创建CheckBoxColumn
我需要保留带/不带过滤器的复选框选择,当我重置datagridview时,checkboxcolumn应该出现一次
public AddressReport1()
{
InitializeComponent();
loadData();//load gridview
}
public void loadData()
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmdSelect = new SqlCommand(@"SELECT ContactId,ReceiverName,City,Address,ContactNo1,ContactNo2,GSTNumber,State FROM tbl_contacts", conn);
SqlDataAdapter da = new SqlDataAdapter(cmdSelect);
DataTable dt = new DataTable();
da.Fill(dt);
dgvAddressReport1.DataSource = dt;
//create checkbox column dynamically in datagridview
DataGridViewCheckBoxColumn select = new DataGridViewCheckBoxColumn();
select.Name = "select";
select.HeaderText = "select";
select.Width = 50;
select.ReadOnly = false;
select.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
//add checkbox column in first row of gridview
dgvAddressReport1.Columns.Insert(0, select);
int dgvindex = dgvAddressReport1.Columns["select"].Index;
MessageBox.Show(dgvindex.ToString());
conn.Close();
}
private void btnBack_Click_1(object sender, EventArgs e)
{
loadData();[enter image description here][1]
}
答案 0 :(得分:0)
首先,您可以在 loadData 方法之外创建 DataGridViewCheckBoxColumn ,也许在构造函数中。所以它只会被创建一次。
要保留复选框选择,可以在数据表或数据库中添加布尔字段。每次单击一行时,只需更新该标志即可。
当你有 DataGridViewCheckBoxColumn 时,重新绑定数据源时,会根据布尔标志自动选中或取消选中此列