在使用文本框筛选记录时维护复选框的状态



我正在开发一个C#窗口应用程序,用于将SQL Server中的记录填充到数据网格视图中,每行都有动态复选框功能。我想通过特定行的复选框来选择选定的行以达到某种目的。到目前为止,我成功地实现了我的目标,但我面临着一个关于保存已检查状态的小问题。

例如,我只想检查那些Name=Max的记录。我在那个文本框中有一个文本框,我用它来调用文本更改事件,比如Query:

try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like @Name order by Pno";
cmd.Parameters.AddWithValue("@Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}

如果我在"按名称筛选"文本框中写入Max,它将返回3条名称以Max开头的记录,就像我上面提到的代码一样。因此,我只使用动态复选框检查了3条记录中的2条,到目前为止,我的代码运行得很好。现在我想检查名称以Ali开头的记录,现在当我在按名称筛选文本框中写入Ali时,它会返回名称类似Ali的行,但问题来了,它会删除我以前检查过的记录,所以我如何保存max和Ali行的检查记录:

在每行中添加动态复选框的代码

DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.Name = "checkBoxColumn";
checkBoxColumn.DataPropertyName = "Report";
checkBoxColumn.HeaderText = "Report";
dataGridView1.Columns.Insert(10, checkBoxColumn);
dataGridView1.RowTemplate.Height = 100;
dataGridView1.Columns[10].Width = 50;

图片:

图像1

图像2

我建议您通过缓存选定的行来实现这一点,首先您应该有一个缓存行的列表:

List<DataGridViewRow> CachedRows = new List<DataGridViewRow>();

然后在单元格值更改上添加事件处理程序,如下所示:

dataGridView1.CellValueChanged += view_CellValueChanged;

并且处理程序应该检查更改的列是否为复选框并选中,应该类似于以下内容:

try
{
if(e.ColumnIndex == indexOfCheckBoxColumn)
{
if((bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == true)
{
CachedRows.Add((DataGridViewRow)dataGridView1.Rows[e.RowIndex].Clone());
}
else if (CachedRows.Contains(dataGridView1.Rows[e.RowIndex]))//Validate if this works, if not you should associate each row with unique key like for example (id) using a dictionary
{
CachedRows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
}
catch(Exception ex)
{
}

然后在过滤器更改后,再次重新添加缓存的行,因此代码变为:

try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like @Name order by Pno";
cmd.Parameters.AddWithValue("@Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
//add folowing
if (CachedRows.Any())
{
dataGridView1.Rows.AddRange(CachedRows.ToArray());
CachedRows.Clear();
}
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}

最新更新