繁体   English   中英

当对datagridview进行C#过滤时,如何将textbox.Text中的文本添加到datagridview.CurrentCell中?

[英]How can I add text from textbox.Text to datagridview.CurrentCell when datagridview is filtered C#?

我不太擅长编码,经过无数研究,我无法弄清楚这一点。

基本上,我要实现的是使用textBox更新特定的单元格。 我根据其他发布内容编写了以下代码(注意:DataBinding是使用VS向导完成的):

    int i;

    private void textBox_TextChanged(object sender, EventArgs e)
    {
        i = dataGridView1.CurrentCell.RowIndex;
    } 

    private void button1_Click(object sender, EventArgs e)
    {
        myDatabaseDataSet.Tables[0].Rows[i][5] = textBox.Text;
    }

上面的代码的问题是,当我使用以下代码过滤dataGridView1时:

    private void comboName_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTableCollection tables = myDatabaseDataSet.Tables;
        DataView view1 = new DataView(tables[0]);
        BindingSource source1 = new BindingSource();
        source1.DataSource = view1;
        dataGridView1.DataSource = source1;
        source1.Filter = "Name='" + comboName.Text.Replace("'", "''") + "'";
    }

该代码将按预期更新dataGridView1.CurrentCell.RowIndex。 这里最大的问题是button1_Click下的代码看不到过滤,因此,它将(例如)写入未过滤表的row [1]而不是已过滤表的row [1]。

任何帮助将不胜感激。

我不太清楚你的问题

您是说更改单元格文本时,该过滤器不适用吗?

尝试将其添加到按钮单击事件中

(myDatabaseDataSet.DataSource as DataTable).DefaultView.RowFilter = "Name='" + comboName.Text.Replace("'", "''") + "'";

根据您的代码,创建原始表的副本。 您不必更新已过滤的表,而是更新原始表myDatabaseDataSet.Tables[0].Rows[i][5] = textBox.Text;

解决方法很明显,我会在这里给您一些想法...

private void button1_Click(object sender, EventArgs e)
{
    myDatabaseDataSet.Tables[0].Rows[i][5] = textBox.Text; // You need to modify this to know which is the correct row to update.
    // Update the filtered table every time you update the main table.
    DataTableCollection tables = myDatabaseDataSet.Tables;
    DataView view1 = new DataView(tables[0]);
    BindingSource source1 = new BindingSource();
    source1.DataSource = view1;
    dataGridView1.DataSource = source1;
    source1.Filter = "Name='" + comboName.Text.Replace("'", "''") + "'";
}

祝好运。

首先,您将必须找到每行唯一的唯一列。 那么您可以像这样选择数据集的dataRow:

int uniqueIDFromDatagrid = (int)dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[uniqueIdentifierColumn.Index].Value;
DataRow targetRow = myDataSet.Tables[0].Rows.OfType<DataRow>().First(x => (int)x["uniqueIdentifierColumn"]== uniqueIDFromDatagrid);

然后您可以像这样在右侧的行和列上更新源:

targetRow[5] = textBox1.Text;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM