I am trying to update my vote count in my SQL Server database each time the "vote" button is pressed after selecting a candidate from my radiobutton list.
The radio button list has 3 candidates, and once a candidate is selected, the vote button is pressed. I want my database to update once the vote button is pressed. However, I have tried many different solutions, and was unsuccessful.
My database has a table with an Id
key (numerical ID), Name
(name of candidates), and Vote
(number of votes of corresponding candidate).
Here is my newest attempt:
public void update_db(string candidate)
{
const string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename =| DataDirectory |\Candidates.mdf; Integrated Security = True";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE Vote SET Vote=Vote+1 WHERE name='" + candidate + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
However, when I run my project, I the following error on the following line:
SqlConnection conn = new SqlConnection(connString);
System.ArgumentException: 'Invalid value for key 'attachdbfilename'.'
I also tried changing UpdateQuery
for SqlDataSource1
from the properties menu on Visual Studio.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Table]"
UpdateCommand="UPDATE Candidates SET Vote = Vote+1 WHERE Vote = @id2 ">
<UpdateParameters>
<asp:ControlParameter ControlID="RadioButtonList1" Name="id2" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>