我正在尝试显示两个日期之间的学生个人出勤记录。当教师选择两个日期时,记录将显示在GridView控件中。但是,我也有其他学生的出勤记录也被显示的问题。我不能只显示学生出勤记录。
一旦老师点击查看按钮,这就是我的C#代码:
protected void ButtonView_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS;Integrated Security=True";
con.Open();
string query1 = "SELECT * FROM attendance WHERE Date between '" + datepicker.Text + "'AND'" + datepicker1.Text + "'";
SqlCommand sqlcomm = new SqlCommand(query1, con);
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
SqlDataReader sdr = sqlcomm.ExecuteReader();
if (sdr.Read())
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Label7.Text = "No records found!!";
}
con.Close();
}
问题在这里:
string query1 = "SELECT * FROM attendance WHERE Date between '" + datepicker.Text + "'AND'" + datepicker1.Text + "'";
我有一个名为Student_ID
的列作为表出席人数的外键。
答案 0 :(得分:3)
string query1 = "SELECT * FROM attendance WHERE Date between @startDate AND @endDate and Student_ID = @studentId";
SqlCommand sqlcomm = new SqlCommand(query1, con);
sqlcomm.Parameters.Add("@startDate", SqlDbType.Date).Value = datepicker.Text;
sqlcomm.Parameters.Add("@endDate", SqlDbType.Date).Value = datepicker1.Text;
sqlcomm.Parameters.Add("@studentId", SqlDbType.Int).Value = 100;