为什么不能使用 C# 删除 sql 中的最后一行?
why can not remove last row in sql by using C#?
我无法删除 table 中的最后一行。我必须添加另一行然后删除上一行。这是我的代码(C# 2010 和 SQL Server 2008 R2)
private void btndelete1_Click(object sender, EventArgs e)
{
{
DialogResult dialogResult = MetroFramework.MetroMessageBox.Show(this," Are you sure to delete this record ? ", "Attention", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
try
{
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
{
SqlCommand delcmd = new SqlCommand();
delcmd.CommandText = "DELETE FROM CustumerTB WHERE CID= "+dataGridViewX1.SelectedRows[0].Cells[0].Value.ToString() + "";
conn.Open();
delcmd.Connection = conn;
delcmd.ExecuteNonQuery();
dataGridViewX1.Rows.RemoveAt(dataGridViewX1.SelectedRows[0].Index);
conn.Close();
}
else if (dialogResult == DialogResult.No)
{
}
}
}
}
}
您无法删除最后一行,因为您的 if
语句:
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
if
语句测试的第一个条件是 dataGridViewX1.Rows.Count
是否大于 1。因此,如果只有一行,则此测试失败,if
语句为假并且删除命令永远不会是 运行。一旦添加新的 运行,行数大于 1,您可以再次删除行。
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
...
换句话说:
如果 datagridview 包含多行
和
如果没有选择最后一行...
您对此有何期待?
我无法删除 table 中的最后一行。我必须添加另一行然后删除上一行。这是我的代码(C# 2010 和 SQL Server 2008 R2)
private void btndelete1_Click(object sender, EventArgs e)
{
{
DialogResult dialogResult = MetroFramework.MetroMessageBox.Show(this," Are you sure to delete this record ? ", "Attention", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
try
{
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
{
SqlCommand delcmd = new SqlCommand();
delcmd.CommandText = "DELETE FROM CustumerTB WHERE CID= "+dataGridViewX1.SelectedRows[0].Cells[0].Value.ToString() + "";
conn.Open();
delcmd.Connection = conn;
delcmd.ExecuteNonQuery();
dataGridViewX1.Rows.RemoveAt(dataGridViewX1.SelectedRows[0].Index);
conn.Close();
}
else if (dialogResult == DialogResult.No)
{
}
}
}
}
}
您无法删除最后一行,因为您的 if
语句:
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
if
语句测试的第一个条件是 dataGridViewX1.Rows.Count
是否大于 1。因此,如果只有一行,则此测试失败,if
语句为假并且删除命令永远不会是 运行。一旦添加新的 运行,行数大于 1,您可以再次删除行。
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)
...
换句话说:
如果 datagridview 包含多行
和
如果没有选择最后一行...
您对此有何期待?