Add, delete, modify, and query of the DataGridView in Winform Development

Source: Internet
Author: User

Add, delete, modify, and query of the DataGridView in Winform Development

The DataGridView is a very powerful control with many usage options. Here is a simple example of addition, deletion, and modification.

Post

Enter the student information on the right and click Add. Add the data to the database and load it to the datagridview. click Modify to load the selected data to the edit box on the right, after modification, click Modify. You can also delete it directly.

Post Code

Public partial class Form1: Form {private static string strConn = "Data Source = 210.26.111.80; Initial Catalog = Test; User ID = sa; Password = wlzx_7975361 "; private SqlConnection conn = new SqlConnection (strConn); private string sqlId = ""; private SqlCommand cmd = null; private SqlDataAdapter da = null; public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {// SQL DataReader studentlist = cmd. executeReader (); // bindingSource1.DataSource = studentlist; // dataGridView1.DataSource = bindingSource1; BindData ();} private void BindData () {if (conn. state = ConnectionState. closed) {conn. open ();} sqlId = "select * from [Student]"; cmd = new SqlCommand (sqlId, conn); da = new SqlDataAdapter (cmd ); dataSet ds = new DataSet (); da. fill (ds, "student"); dataGridView1. AutoGenerateColumns = false; // This row does not need to be automatically bound to a data column. The data column is specified in the items set of the dataGridView attribute and must be placed before binding data, it is useless to put it behind. // dataGridView1.DataSource = ds. tables ["Student"]; albe is used directly to bind the data. The effect of the following two lines of code is the same as that of the dataGridView1.DataSource = ds; // If Dataset is used, DataMember must be specified, because DataSet is a set of DataTable, and datagridview can only bind one datatable dataGridView1.DataMember = "Student"; if (conn. state = ConnectionState. open) {conn. close () ;}} private void btn Add_Click (object sender, EventArgs e) {try {string username = textBox1.Text; string homeaddress = textBox2.Text; string info = textBox3.Text; conn. open (); // prepare an SQL statement, where only one variable and one parameter are represented here starting. SqlId = "Insert into Student (StudenTnAME, HomeAddress, Content) values (@ StudenTnAME, @ HomeAddress, @ Content)"; // create a parameter array, and use the values in curly brackets to initialize the array SqlParameter [] parameters = new [] {// here also has an initialization process, copy the name to @ name, the following is the same new SqlParameter ("@ StudenTnAME", username ), // The name on the right of the parentheses is the user input value new SqlParameter ("@ HomeAddress", homeaddress), new SqlParameter ("@ Content ", info)}; cmd = conn. createCommand (); // put the SQL string into the command using the object attributes (set the SQL statement to be executed on the data source) cmd. commandText = sqlId; // obtain the parameter set using the Parameters attribute of the object, and then append the value of the parameter set to the cmd. parameters. addRange (parameters); int x = cmd. executeNonQuery (); if (x = 1) {// if the addition is successful, a message is displayed to the user. show ("added successfully"); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = "" ;}} catch (Exception ex) {MessageBox. show (ex. message);} finally {conn. close () ;}// click the selected row and put the content in the edit box. private void maid cellclick (object sender, DataGridViewCellEventArgs e) {textBox1.Text = maid [e. rowIndex]. cells ["studentname"]. value. toString (); textBox2.Text = maid [e. rowIndex]. cells ["homeaddress"]. value. toString (); textBox3.Text = maid [e. rowIndex]. cells ["info"]. value. toString () ;}// save private void btnUpdate_Click (object sender, EventArgs e) {try {conn. open (); // prepare an SQL statement and concatenate an SQL string. This is different from passing the parameter sqlId = "update Student set StudenTnAME = '" + textBox1.Text + "' in ADD "', homeAddress = '"+ textBox2.Text +"', Content = '"+ textBox3.Text +" 'where ID = "+ Convert. toInt32 (maid. cells [0]. value. toString (); cmd = conn. createCommand (); // put the SQL string into the command using the object attributes (set the SQL statement to be executed on the data source) cmd. commandText = sqlId; int x = cmd. executeNonQuery (); if (x = 1) {// if the addition is successful, a message is displayed to the user. show ("modified successfully"); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; BindData () ;}} catch (Exception ex) {MessageBox. show (ex. message);} finally {conn. close () ;}// Delete the selected private void btnDel_Click (object sender, EventArgs e) {try {conn. open (); // prepare an SQL statement and concatenate an SQL string. This is different from passing the parameter sqlId = "delete from Student where ID =" + Convert. toInt32 (maid. cells [0]. value. toString (); cmd = conn. createCommand (); // put the SQL string into the command using the object attributes (set the SQL statement to be executed on the data source) cmd. commandText = sqlId; int x = cmd. executeNonQuery (); if (x = 1) {// if the addition is successful, a message is displayed to the user. show ("deleted successfully"); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; BindData () ;}} catch (Exception ex) {MessageBox. show (ex. message);} finally {conn. close ();}}}

This is simple, but we can see that data operations are cumbersome. The following blog posts will encapsulate a database operation class for operations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.