ASP.Net + C# - 如果MySQL查询没有返回任何行,请执行

时间:2014-09-02 18:10:32

标签: c# mysql asp.net datatable dataadapter

我有一个查询MySQL表并在图表中显示输出的函数。

但是,如果没有返回任何查询,我想在lblError2中输出一条消息。我试过使用下面的代码,但似乎没有用。它什么也没输出。

代码:

protected void chart(int moduleID)
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    string comm = "SELECT * FROM scores WHERE test_id=0 AND module_id=@ModuleID AND user_id=@UserID";
    MySqlCommand mySqlCommand = new MySqlCommand(comm, conn);
    mySqlCommand.Parameters.Add(new MySqlParameter("@ModuleID", moduleID));
    mySqlCommand.Parameters.Add(new MySqlParameter("@UserID", Session["UserID"]));

    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
    DataTable ds = new DataTable();

    Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
    Chart1.ChartAreas["ChartArea1"].AxisX.Title = "attempt no.";
    Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
    Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
    Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
    Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;
    Chart1.Series["Series1"].BorderWidth = 2;

    try
    {
        conn.Open();
        dataAdapter.Fill(ds);

        if (ds.Rows.Count > 0)
        {
            Chart1.DataSource = ds;
            Chart1.Series["Series1"].YValueMembers = "score";
            Chart1.DataBind();
            Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = ds.Rows.Count;
        }
        else
        {
            Chart1.Visible = false;
            lblError2.Text = "No results found.";
        }
    }
    catch
    {
        lblError.Text = "Database connection error. Unable to obtain data at the moment.";
    }
    finally
    {
        conn.Close();
    }
}

0 个答案:

没有答案