moe
moe

Reputation: 5249

check if record columns have some special values

I want to check to see if some of the fields have some unique values - for instance, I want to check if field1, field2 in my table have a value of "YES". If both of them have "Yes" then I want to call some function, but if one of them has "No" value then I want to call some other function. Note in my select statement, I am passing an ID from the query-string. How can I do this?

protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e) {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter("SELECT ID, Field1, Field2 from MyTabel WHERE ID = '" + Request.QueryString["ID"] + "'", con);
    DataTable dt = new DataTable();
    da.Fill(dt);
}

Upvotes: 1

Views: 169

Answers (1)

mohsen dorparasti
mohsen dorparasti

Reputation: 8405

If figuring out whether a specific set of criteria exists or not in a given record is all you need, then I can suggest you doing this check on Database side and then using ExecuteScalar to get the result:

using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
    using(SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTabel WHERE ID =@ID And (Field1='Yes' And Field2='Yes')" , con))
    {
        cmd.parameters.Add("@ID",Request.QueryString["ID"]);

        con.open();

        int result = cmd.ExecuteScalar();

        con.close();

        if(result == 1)
            // condition exists
            // so call success function
        else
            // call failure function
    }
}

Update:

This may not be directly related to the question but to get record Id from detailsView, you need to go through 2 steps:

  1. Set the datakeynames property for the detailsView to the name of your table's primary key name – in this case, ID.

    <asp:detailsview datakeynames="ID"
    
  2. Now you can access the selected Id by

    int id = (int)detailsView.SelectedValue;
    

Check here for more information.

Upvotes: 4

Related Questions