简体   繁体   中英

C# Datagridview using winforms

I want to delete a record from a DataGridView , when a record is selected. I get this exception error when I use the code below,

string conStrings = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ImpiDb.mdf;Integrated Security=True;Connect Timeout=30";
string sql = "Select * from tblImpi";
con = new SqlConnection(conStrings);
con.Open();
dataAdapter = new SqlDataAdapter(sql, con);
//ImpiDbDataSet impds = new ImpiDbDataSet();
ds = new DataSet();
SqlCommandBuilder cmdb = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(ds, "tblImpi");
BindingSource bndS = new BindingSource();
bndS.DataSource = ds.Tables["tblImpi"];
impdg.DataSource = bndS;

delete button

private void btnDelete_Click(object sender, EventArgs e)
{

    if (MessageBox.Show("I you sure you want to delete this record?","Delete",MessageBoxButtons.YesNo)==DialogResult.Yes)
    {
        impdg.Rows.RemoveAt(impdg.SelectedRows[0].Index);
        dataAdapter.Update(ds,"tblImpi");
    }
}

I suppose you want to delete a record but removing it from the Grid does not remove it from the table.

Don't use the DataGridView directly to interact with your datasource but do it this way.

var table = ds.Tables["tblImpi"];
var row = impdg.SelectedRows[0];
var item = (DataRowView)row.DataBoundItem;
item.Delete();

// I am not 100% sure that row.DataBoundItem returns a DataRowView,
// if it returns a DataRow you can use
table.Rows.Remove(item); 
// instead of item.Delete();

here is answer for the question.

private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("I you sure you want to delete this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    impdg.Rows.RemoveAt(impdg.SelectedRows[0].Index);
                    dataAdapter.Update(dt1);



                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

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