【发布时间】:2016-01-30 19:00:51
【问题描述】:
我真的被卡住了,这里的书籍或步骤都不够人性化,无法解释如何使用 C# 从数据网格对象中删除数据
从各种书籍和四个线程中,我设法得到了这个编码,但它无法执行 sql 命令,我有一个表调用'SpellingList',两列一是 ID,另一列是单词,我只想要做的是从数据网格中删除一行。
谁能给我指出正确的方向,一旦我解决了这个问题,我会上传一些简单易学的基本教程,以便其他新手可以按照这个示例进行操作。
我用过这个帖子How to delete a selected DataGridViewRow and update a connected database table?
和 MCSD Certificaiton Toolkit Exam 70-483 book Page 392 ,所有尝试都失败了。
如果我注释掉 if(dataGridView1.SelectedRows.Count > 0) 行,这里有一个 catch 22,我得到索引超出范围错误。
private void btnDelete_Click(object sender, EventArgs e)
{
// My SQL connectionString
SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True");
myConnection.Open();
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if(dataGridView1.SelectedRows.Count > 0)
{
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
// your code for deleting it from the database
string sql = "DELETE FROM SpellingList WHERE Words =" + selectedIndex;
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = myConnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "@Words";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
deleteRecord.Connection.Close();
wordsDataSet.GetChanges();
// booksDataset1.GetChanges();
spellingListTableAdapter.Fill(wordsDataSet.SpellingList);
}// end of if
// then your code for refreshing the DataGridView
}// end of for each statement
myConnection.Close();
}// end of delete Button
【问题讨论】:
-
最初如何填充网格?
标签: c# datagrid delete-row