如何自动将数据从选定的DataGridView行显示到TextBox,而无需为单独的TextBox声明值?

时间:2019-06-28 08:07:33

标签: c# winforms

如何自动显示分配给DataGridView的临时表中的数据,选择一行并将其显示在TextBox中,  无需为单独的TextBox声明值(例如,TextBox1.text = ...),只需要输入 表和同一个文本框的名称?

这是我的主意,确实有效:

DataTable dt = new DataTable();
dt.Columns.Add("sv_ID");
dt.Columns.Add("sv_Name");
dt.Columns.Add("sv_Address");

dt.Rows.Add("0", "duy", "hungyen");
dt.Rows.Add("1", "duy1", "hungyen1");
dt.Rows.Add("2", "duy2", "hungyen2");
dt.Rows.Add("3", "duy3", "hungyen3");
dt.Rows.Add("4", "duy4", "hungyen4");
dt.Rows.Add("5", "duy5", "hungyen5");
dt.Rows.Add("6", "duy6", "hungyen6");

dataGridView1.DataSource = dt;

private void dataGridView1_SelectionChanged(object sender, EventArgs e){
    int n = this.Controls.Count;
    int n1 = dt.Columns.Count;
    int _rowsl = dataGridView1.CurrentRow.Index;
    if (_rowsl >= 0){
        for (int i = 0; i <= n - 1; i++){
            for (int k = 0; k <= n - 1; k++){
                if (this.Controls[i].Name == dt.Columns[k].ColumnName){
                    this.Controls[i].Text = 
                 dataGridView1.Rows[_rowsl].Cells[k].Value.ToString();
                }
            }
            dataGridView1.DataSource = dt;
         }
    }
}

0 个答案:

没有答案