0
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
        try
        {
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=  C:\\Users\\JAY\\Desktop\\Employee.mdb");
            OleDbCommand cmd = new OleDbCommand("select * from Emp_Details WHERE DOB="+ monthCalendar1.SelectionRange.Start.ToShortDateString() +"", con);
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Emp_Details");
            txtEmployeeNo.Text = ds.Tables[0].Rows[0][0].ToString();
            txtName.Text = ds.Tables[0].Rows[0][1].ToString();
            txtAddress.Text = ds.Tables[0].Rows[0][2].ToString();
            comboBox1.Text = ds.Tables[0].Rows[0][3].ToString();
            txtMobNo.Text = ds.Tables[0].Rows[0][4].ToString();


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

基本上我想通过月历控件检索数据...但是当我单击月历控件的日期时出现异常,位置 0 处没有行

4

1 回答 1

0

不要使用内联参数,您可以使用参数化查询,如下所示

using (var con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=  C:\Users\JAY\Desktop\Employee.mdb"))
using (var cmd = new OleDbCommand("select * from Emp_Details WHERE DOB= ?", con))
{
    cmd.Parameters.AddWithValue("@P1", monthCalendar1.SelectionRange.Start);
    using (var da = new OleDbDataAdapter(cmd))
    {
        da.Fill(ds, "Emp_Details");
        if (ds.Tables["Emp_Details"] !=null && ds.Tables["Emp_Details"].Rows.Count>0)
        {
            DataRow dr = ds.Tables["Emp_Details"].Rows[0];
            txtEmployeeNo.Text = dr[0].ToString();
            txtName.Text = dr[1].ToString();
            txtAddress.Text = dr[2].ToString();
            comboBox1.Text = dr[3].ToString();
            txtMobNo.Text = dr[4].ToString();
        }
    }
} 
于 2013-05-16T10:13:46.290 回答