簡體   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