简体   繁体   中英

How to select row from DataGridView with DB to a new DataGridView in C#

I have two DataGridViews,

  1. datagridviewDoses All dishes from DB
  2. datagridviewDoseOrder is empty

I would like as soon as I press the button line from datagridviewDoses. The line will move to datagridviewDoseOrder. The buttons I added, I can not move the line to -datagridviewDoseOrder.

  private void AddColumn()
{
    DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
    buttonColumn.HeaderText = "בחר מנה";
    buttonColumn.Name = "בחר מנה";
    buttonColumn.Text = "בחר מנה";
    buttonColumn.UseColumnTextForButtonValue = true;
    dataGridViewDoses.Columns.Add(buttonColumn);
    dataGridViewDoses.CellClick += new DataGridViewCellEventHandler(dataGridViewDoses_CellClick);
}
void dataGridViewDoses_CellClick(object sender, DataGridViewCellEventArgs e)
{

}

I was able to recreate your problem and solve it as following:

An example class as the data source for each dgview.

public class Example
{
  public string Foo { get; set; }
  public string Bar { get; set; }
}

The form displaying two DataGridViews.

public Form1()
{
  InitializeComponent();
  this.First = new BindingList<Example>()
  {
    new Example() { Foo = "foo1", Bar = "bar1" },
    new Example() { Foo = "foo2", Bar = "bar2" }
  };
  this.Second = new BindingList<Example>();

  this.dataGridView1.DataSource = this.First;
  this.dataGridView2.DataSource = this.Second;

  DataGridViewButtonColumn btnCol = new DataGridViewButtonColumn();
  btnCol.HeaderText = "Transfer";
  btnCol.Name = "Transfer";
  btnCol.Text = "Transfer";
  btnCol.UseColumnTextForButtonValue = true;
  this.dataGridView1.Columns.Add(btnCol);
  this.dataGridView1.CellClick += new DataGridViewCellEventHandler(col_Click);
}

public BindingList<Example> First { get; set; }
public BindingList<Example> Second { get; set; }

public void col_Click(object sender, DataGridViewCellEventArgs e)
{
  if (e.ColumnIndex == 0) // The button column somehow is column 0, Foo is 1, and Bar is 2.
  {
    this.Second.Clear();
    this.Second.Add(this.First[e.RowIndex]);
  }
}

By clicking on a button, that row's data is moved over to the second DataGridView. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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