2015-12-11 2 views
0

Я создал datagridview, который получает все данные из базы данных MySQL Workbench. Ниже этого datagridview я создал еще один datagrid с теми же столбцами. Для этого я создал функцию копирования, которая при выборе строк формирует первое datagridview, копирует выбранные строки во второй datgrid.Удалить строку в DataGridView C# с использованием значения текстового поля

Я создал текстовые поля, которые отображают строки, выбранные во втором datagridview.

Все, что я хочу сделать, это получить, получить значения из текстовых полей, сопоставить их в первом datagridview и после нажатия кнопки удаления удалить уважаемую строку из первого datagridview и уважать из базы данных.

Я новичок в C#, поэтому любая помощь будет оценена. enter image description here

Исходный код:

namespace panelApplication 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
    { 
     InitializeComponent(); 
    } 
    private void copy_Click(object sender, EventArgs e) 
    { 
     // dataGridView2.Rows.Clear(); (code used if you want to delete previous selections) 
     foreach (DataGridViewRow item in dataGridView1.Rows) 
     { 
      if (item.Selected == true) 
      { 
       int n = dataGridView2.Rows.Add(); 
       dataGridView2.Rows[n].Cells[0].Value = item.Cells[0].Value.ToString(); 
       dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString(); 
       dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString(); 
      } 
     } 
    } 
    public void fetch_Click(object sender, EventArgs e) 
    { 
     this.productsTableAdapter.Fill(this.productsDataset.products); 
     productsDataset dt = new productsDataset(); 
     foreach (DataRow item in dt.products.Rows) 
     { 
      int n = dataGridView1.Rows.Add(); 
      dataGridView1.Rows[n].Cells[1].Value = item["product_id"].ToString(); 
      dataGridView1.Rows[n].Cells[2].Value = item["product_name"].ToString(); 
      dataGridView1.Rows[n].Cells[3].Value = item["category_id"].ToString(); 
     } 
    } 
    private void delete_btn_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex) // error on this line. 
      { 

      } 
     } 
     catch (System.Exception) 
     { 
      MessageBox.Show("Not able to Delete"); 
     } 
    } 
    private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.RowIndex >= 0) 
     { 
      DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex]; 
      product_idTxtbx.Text = row.Cells["product_id"].Value.ToString(); 
      proName_txtbx.Text = row.Cells["product_name"].Value.ToString(); 
      catID_txtbx.Text = row.Cells["category_id"].Value.ToString(); 
     } 
    } 
    private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.RowIndex >= 0) 
     { 
      DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex]; 
      product_idTxtbx.Text = row.Cells["product_id"].Value.ToString(); 
      proName_txtbx.Text = row.Cells["product_name"].Value.ToString(); 
      catID_txtbx.Text = row.Cells["category_id"].Value.ToString(); 
     } 
    } 
    private void delete2_Click(object sender, EventArgs e) 
    { 
    //  if (dataGridView1.Rows["row.index"].Cells["productidDG"].Value.ToString() == product_idTxtbx.Text) 
     { 

     } 
    } 
} 

}

+0

Можете ли вы показать нам, что вы пытались? – Haris

+0

Посмотрите на этот ответ: http://stackoverflow.com/a/33451345/2946329 –

ответ

0

На удалении события нажатия кнопки btn_OnDelete() найти то GridView индекса найти все идентификаторы по индексу строки. Затем сравните каждый GridView идентификатор строки в текстовое поле идентификатора элемента как:

if(GridView1.Rows.Cell[0].Text == TextBox1.tex) 
{ 
    // Delete Query here 
} 

для кода доли полного решения со мной. смотрите здесь демо ссылка: CRUD Operation link

+0

Аман Я добавил код. –

0

Вы должны использовать этот код:

<asp:Button ID="delete" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Delete" /> 
    private void delete_btn_Click(object sender, EventArgs e) 
     { 
      //incase you need the row index 
     int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex; 
     int Prod_Id= Convert.ToInt32(e.CommandArgument); 
     //followed by your code 
      try 
      { 
       // Then Compare your Id here in this if condition 
       // if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex 
       if (Prod_id == Convert.ToInt32(TextBox1.text)) // error on this line. 
       { 
        // User Code Here 
       } 
      } 
      catch (System.Exception) 
      { 
       MessageBox.Show("Not able to Delete"); 
      } 
     } 
+0

Я надеюсь, что это работает правильно. – Aman

0

пожалуйста сделать свой код, как показано ниже

private void delete_btn_Click(object sender, EventArgs e) 
    { 
     try 
     { 
     foreach (GridViewRow row in dataGridView1.Rows) 
     { 
      if (row.RowType == DataControlRowType.DataRow) 
      { 
      if (row.Cell[0].value == TextBox1.tex) 
      { 
       //delete opration here for TextBox1.tex/row.Cell[0].Text(Product_id) 
       break; 
      } 
      } 

     } 

     } 
     catch (System.Exception) 
     { 
      MessageBox.Show("Not able to Delete"); 
     } 
    } 
+0

Он выдает сообщение об ошибке: «DataGridViewRow не содержит защиты для ячейки» –

+0

теперь добавить одно условие –

+0

По-прежнему такая же ошибка. «DataGridViewRow не содержит защиту для RowType» –

Смежные вопросы