尝试捕获永远不会进入catch块

时间:2021-10-09 22:24:00

The problem with the code below is that I never see my catch code execute. If my id doesn't exist, it shows a empty datagrid. What goes wrong?

下面代码的问题是我从未看到我的catch代码执行。如果我的id不存在,则显示空数据网格。出了什么问题?

private void btnSearch_Click(object sender, EventArgs e)
{
    try
    {
        this.Cursor = Cursors.WaitCursor;
        SqlConnectie vandaag = new SqlConnectie();
        vandaag.Connection();
        SqlDataAdapter sda = new SqlDataAdapter("select ID, VERSIE, SB, NAAM, M_DATUM, V_DATUM from RE1 where ID=" + tbRecept.Text, SqlConnectie.conn);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dgvTemp.DataSource = dt;
        SqlConnectie.conn.Close();
        this.Cursor = Cursors.Default;
    }

    catch
    {
        MessageBox.Show("ID doesn't exist");
    }
}

1 个解决方案

#1


Why do you expect an exception if no row is returned from database? It is perfectly valid to get an empty resultset, the dataadapter will return an empty DataTable.

如果没有从数据库返回任何行,为什么会出现异常?获取空结果集是完全有效的,dataadapter将返回一个空的DataTable。

You could check it:

你可以检查一下:

DataTable dt = new DataTable();
sda.Fill(dt);
dgvTemp.DataSource = dt;
if(dt.Rows.Count == 0)
    MessageBox.Show("ID doesn't exist");

#1


Why do you expect an exception if no row is returned from database? It is perfectly valid to get an empty resultset, the dataadapter will return an empty DataTable.

如果没有从数据库返回任何行,为什么会出现异常?获取空结果集是完全有效的,dataadapter将返回一个空的DataTable。

You could check it:

你可以检查一下:

DataTable dt = new DataTable();
sda.Fill(dt);
dgvTemp.DataSource = dt;
if(dt.Rows.Count == 0)
    MessageBox.Show("ID doesn't exist");