Jump to content

Updating Database with Button_Click

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
ctote

ctote

    Newbie

  • Members
  • Pip
  • 5 posts
I have a datagrid showing my items - I want to modify a field in the database when the user clicks a button. So if row 3 is selected, I want to modify "SomeField" in Row3 to True. Is there an easy way to accomplish that?

#2
ctote

ctote

    Newbie

  • Members
  • Pip
  • 5 posts
I've added this:



 private void button_Checkout_Click(object sender, EventArgs e)
    {
      DataGridViewRow row = dataGridView1.SelectedRows[0];
      MessageBox.Show(Convert.ToString((row.Cells[0].Value)));
      row.Cells[0].Value = "Pen-Laptop3";
....

but I can't get it to write to the database. It modifies my application gridview fine, but nothing changes at the server. Also, I can't figure out how to select column #4 for example. I can only work with column #0 it seems.

#3
QuackWare

QuackWare

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
Well if you want to modify the "SomeField" column name in your selected row it would be:

row.Cells["SomeField"].Value = "Pen-Laptop3";

As for writing to the database, are you getting the datagridview data source and uploading that or are you taking a row out of the datagrid and trying to upload that

#4
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
Note that you have to AcceptChanges() in the DataSet, and then SubmitChanges() in the DataBase.

Are you using a LINQ to SQL connection?
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#5
ctote

ctote

    Newbie

  • Members
  • Pip
  • 5 posts
I'm not sure how I'm connecting to the database. The only database connections I've started are through the databinding features.

As for creating an actual sql connection, I'm pretty lost on that. I know the credentials of my SQL server, but I don't know how to code an SQL connection.

#6
ctote

ctote

    Newbie

  • Members
  • Pip
  • 5 posts
Got it working - here's my code for anyone else who may need it:
/*
    SQL Connection and Modification with real examples
*/

/*********/
using System.Data.SqlClient;
/*********/

//SQL connection string
/*****
Data Source = YourServerName\\DataBaseInstance
Initial Catalog = TheDatabaseName
Integrated Security = SSPI (uses current logon credentials to authenticate with Database Server)
******/
string cs = "Data Source=REG-PENTREE1\\SQLEXPRESS;Initial Catalog=reg_checkout;Integrated Security=SSPI";

//Create a connection
SqlConnection conn = new SqlConnection(cs);

//Open the SQL connection
conn.Open();

//Create SQL command to be sent
SqlCommand cmd = new SqlCommand("UPDATE Laptops SET isCheckedOut=1 WHERE name='pen-laptop1'", conn);

//Execute command
cmd.ExecuteNonQuery();