【问题标题】:why can not remove last row in sql by using C#?为什么不能使用 C# 删除 sql 中的最后一行?
【发布时间】:2015-05-13 08:10:46
【问题描述】:

我无法删除表格中的最后一行。我必须添加另一行,然后删除前一行。这是我的代码(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)
                {

                }
            }
        }
    }
}

【问题讨论】:

  • 如果你使用的是sql server,为什么mysql被标记?请不要标记不相关的产品

标签: c# sql-server-2008 c#-4.0


【解决方案1】:
if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)

...

换句话说:
如果 datagridview 包含多于一行

如果最后一行没有被选中...

您对此有何期待?

【讨论】:

  • if (dataGridViewX1.Rows.Count > 0 && dataGridViewX1.SelectedRows[0].Index != -1 )
【解决方案2】:

由于您的if 语句,您无法删除最后一行:

if (dataGridViewX1.Rows.Count > 1 && dataGridViewX1.SelectedRows[0].Index != dataGridViewX1.Rows.Count - 1)

if 语句测试的第一个条件是dataGridViewX1.Rows.Count 是否大于 1。因此,如果您只有一行,则此测试失败,if 语句为 false,并且永远不会运行删除命令。一旦添加新的运行,行数就会大于 1,您可以再次删除行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多