Click here to Skip to main content
16,012,168 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to update an integer value by incrementing with value of 1 using a checkbox by checking it, it runs but it doesn't update the value.
C#
    //code behind the button
    StringCollection idCollection = new StringCollection();
    string  strid = string .Empty ;
    //loop through gridview to find checked rows
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        CheckBox chckupdate = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chckhere");
        if (chckupdate != null)
        {
            if (chckupdate.Checked)
            {
                strid = GridView1.Rows[i].Cells[1].Text;
                idCollection.Add(strid);
            }
        }
    }
    if (idCollection.Count > 0)
    {
        //call method to update records
        updaterecords(idCollection);
        //rebind the gridview
        GridView1.DataBind();
    }
    else
    {
        //lblmsg.Text = "Please select your favourate candidates";
    }
}


 private void updaterecords(StringCollection idCollection)
 {
//  create sqlconnection and sqlcommand
    SqlConnection conn=new SqlConnection(strconnection);
    SqlCommand cmd=new SqlCommand();
    string ids = "";

    foreach (string id in idCollection)
    {
    ids+=id.ToString()+",";
    }
    try
    {
        string test = ids.Substring(0, ids.LastIndexOf(","));
        string update = "update results set votes=votes+1 where id in (" + test + ")";
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = update;
        cmd.Connection = conn;
        conn.Open();
        cmd.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        string errormsg = "Error in ballot cast";
        errormsg += ex.Message;
        //throw new Exception(errormsg);
    }
    finally
    {
        conn.Close();
        Response.Redirect("~/Castvotes.aspx");
    }
}
Posted
Updated 23-Aug-11 22:50pm
v7

1 solution

What is here @ sign for? Make it like this.
SQL
"update results set votes=votes+1 where id in (" + test + ")"

Moreover, your question is not clear. What do you mean by - my primary key appear as foreign key? Try to rephrase your question.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900