Hello Forum,
I tried to bind data to GridView based on the dropdown list and selected dates and it is working.
But I added a statement that may bind data to GridView based on admin who creates other users, dropdown list and dates selected; I AM TRYING TO AVOID OTHER USERS TO VIEW OR SEE RECORDS OF USERS WHO ARE NOT LINKED TO HIM. After this, I noticed that data was displayed based on the admin when I selected value in the dropdown list. But when I selected From and To dates, it gave me an error.
Incorrect syntax near the keyword WHERE
protected void Button2_Click(object sender, EventArgs e)
{
if (ddlTables.SelectedIndex > 0)
{
string query = "";
if (ddlTables.SelectedValue.ToLower() == "cards")
{
query = "SELECT TOP 5 email,UserRole,Name,image FROM Users WHERE CreatedBy=@CreatedBy OR @CreatedBy = ''";
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(Dat.Text))
{
query += " WHERE CreateDate BETWEEN @From AND @To";
}
}
if (ddlTables.SelectedValue.ToLower() == "certificates")
{
query = "SELECT TOP 5 fullname,fone,chasis,type_v, mal FROM Report";
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(Dat.Text))
{
query += " WHERE dat BETWEEN @From AND @To";
}
}
if (ddlTables.SelectedValue.ToLower() == "reciepts")
{
query = "";
}
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CreatedBy", user.Text);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(Dat.Text))
{
cmd.Parameters.AddWithValue("@From", TextBox1.Text);
cmd.Parameters.AddWithValue("@To", Dat.Text);
}
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}