Introduction

This article explains how to insert Select, Update and Delete data into a MySQL database from an ASP.NET web application.

So, let's proceed with the following procedure:

Now, open a MySQLAdmin Page then select "Create A New Table” -> "View" -> ”Table Structure for Table `student`”.

  1. CREATE TABLE IF NOT EXISTS `student` (
  2. `SID` int(100) NOT NULL AUTO_INCREMENT,
  3. `Name` varchar(100) NOT NULL,
  4. `Address` varchar(500) NOT NULL,
  5. `Email` varchar(100) NOT NULL,
  6. `Mobile` varchar(25) NOT NULL,
  7. PRIMARY KEY (`SID`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=31 ;



Open your instance of Visual Studio 2012, and create a new ASP.NET Web application. Name the project “MYSQLCRUDApplication ", as shown in the following figure:



In the code behind file (Student.aspx.cs) write the code as in the following.

Student.aspx

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
  2. CodeBehind="Student.aspx.cs" Inherits="MYSQLCRUDApplication.Student" %>
  3. <asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">
  4. Simple Insert Select Update and Delete in ASP.NET using MySQL Database
  5. </asp:Content>
  6. <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
  7. </asp:Content>
  8. <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
  9. <table>
  10. <tr>
  11. <td class="td">Name:</td>
  12. <td>
  13. <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
  14. <td>
  15. <asp:Label ID="lblSID" runat="server" Visible="false"></asp:Label> </td>
  16. </tr>
  17. <tr>
  18. <td class="td">Address:</td>
  19. <td>
  20. <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
  21. <td> </td>
  22. </tr>
  23. <tr>
  24. <td class="td">Mobile:</td>
  25. <td>
  26. <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
  27. <td> </td>
  28. </tr>
  29. <tr>
  30. <td class="td">Email ID:</td>
  31. <td>
  32. <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
  33. <td> </td>
  34. </tr>
  35. <tr>
  36. <td></td>
  37. <td>
  38. <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
  39. <asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false"
  40. OnClick="btnUpdate_Click" />
  41. <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>
  42. <td></td>
  43. </tr>
  44. </table>
  45. <div style="padding: 10px; margin: 0px; width: 100%;">
  46. <p>
  47. Total Student:<asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>
  48. </p>
  49. <asp:GridView ID="GridViewStudent" runat="server" DataKeyNames="SID"
  50. OnSelectedIndexChanged="GridViewStudent_SelectedIndexChanged"
  51. OnRowDeleting="GridViewStudent_RowDeleting">
  52. <Columns>
  53. <asp:CommandField HeaderText="Update" ShowSelectButton="True" />
  54. <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
  55. </Columns>
  56. </asp:GridView>
  57. </div>
  58. </asp:Content>

In the Web.config file create the connection string as in the following.

Web.config

  1. <connectionStrings>
  2. <add name="ConnectionString"
  3. connectionString="Server=localhost;userid=root;password=;Database=Testdb"
  4. providerName="MySql.Data.MySqlClient"/>
  5. </connectionStrings>

Now, in the code behind file “Student.aspx.cs “ use the following code.

Student.aspx.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using MySql.Data.MySqlClient;
  10. namespace MYSQLCRUDApplication
  11. {
  12. public partial class Student : System.Web.UI.Page
  13. {
  14. #region MySqlConnection Connection and Page Lode
  15. MySqlConnection conn = new
  16. MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
  17. protected void Page_Load(object sender, EventArgs e)
  18. {
  19. Try
  20. {
  21. if (!Page.IsPostBack)
  22. {
  23. BindGridView();
  24. }
  25. }
  26. catch (Exception ex)
  27. {
  28. ShowMessage(ex.Message);
  29. }
  30. }
  31. #endregion
  32. #region show message
  33. /// <summary>
  34. /// This function is used for show message.
  35. /// </summary>
  36. /// <param name="msg"></param>
  37. void ShowMessage(string msg)
  38. {
  39. ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
  40. language='javascript'>alert('" + msg + "');</script>");
  41. }
  42. /// <summary>
  43. /// This Function is used TextBox Empty.
  44. /// </summary>
  45. void clear()
  46. {
  47. txtName.Text = string.Empty; txtAddress.Text = string.Empty; txtMobile.Text = string.Empty;
  48. txtEmail.Text = string.Empty;
  49. txtName.Focus();
  50. }
  51. #endregion
  52. #region bind data to GridViewStudent
  53. private void BindGridView()
  54. {
  55. Try
  56. {
  57. if (conn.State == ConnectionState.Closed)
  58. {
  59. conn.Open();
  60. }
  61. MySqlCommand cmd = new MySqlCommand("Select * from Student ORDER BY SID DESC;",
  62. conn);
  63. MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
  64. DataSet ds = new DataSet();
  65. adp.Fill(ds);
  66. GridViewStudent.DataSource = ds;
  67. GridViewStudent.DataBind();
  68. lbltotalcount.Text = GridViewStudent.Rows.Count.ToString();
  69. }
  70. catch (MySqlException ex)
  71. {
  72. ShowMessage(ex.Message);
  73. }
  74. Finally
  75. {
  76. if (conn.State == ConnectionState.Open)
  77. {
  78. conn.Close();
  79. }
  80. }
  81. }
  82. #endregion
  83. #region Insert Data
  84. /// <summary>
  85. /// this code used to Student Data insert in MYSQL Database
  86. /// </summary>
  87. /// <param name="sender"></param>
  88. /// <param name="e"></param>
  89. protected void btnSubmit_Click(object sender, EventArgs e)
  90. {
  91. Try
  92. {
  93. conn.Open();
  94. MySqlCommand cmd = new MySqlCommand("Insert into student (Name,Address,Mobile,Email )
  95. values (@Name,@Address,@Mobile,@Email)", conn);
  96. cmd.Parameters.AddWithValue("@Name",txtName.Text);
  97. cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
  98. cmd.Parameters.AddWithValue("@Mobile",txtMobile.Text);
  99. cmd.Parameters.AddWithValue("@Email",txtEmail.Text);
  100. cmd.ExecuteNonQuery();
  101. cmd.Dispose();
  102. ShowMessage("Registered successfully......!");
  103. clear();
  104. BindGridView();
  105. }
  106. catch (MySqlException ex)
  107. {
  108. ShowMessage(ex.Message);
  109. }
  110. Finally
  111. {
  112. conn.Close();
  113. }
  114. }
  115. #endregion
  116. #region SelectedIndexChanged
  117. /// <summary>
  118. /// this code used to GridViewRow SelectedIndexChanged value show textbox
  119. /// </summary>
  120. /// <param name="sender"></param>
  121. /// <param name="e"></param>
  122. protected void GridViewStudent_SelectedIndexChanged(object sender, EventArgs e)
  123. {
  124. GridViewRow row = GridViewStudent.SelectedRow;
  125. lblSID.Text = row.Cells[2].Text;
  126. txtName.Text = row.Cells[3].Text;
  127. txtAddress.Text = row.Cells[4].Text;
  128. txtEmail.Text = row.Cells[5].Text;
  129. txtMobile.Text = row.Cells[6].Text;
  130. btnSubmit.Visible = false;
  131. btnUpdate.Visible = true;
  132. }
  133. #endregion
  134. #region Delete Student Data
  135. /// <summary>
  136. /// This code used to GridViewStudent_RowDeleting Student Data Delete
  137. /// </summary>
  138. /// <param name="sender"></param>
  139. /// <param name="e"></param>
  140. protected void GridViewStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
  141. {
  142. Try
  143. {
  144. conn.Open();
  145. int SID = Convert.ToInt32(GridViewStudent.DataKeys[e.RowIndex].Value);
  146. MySqlCommand cmd = new MySqlCommand("Delete From student where SID='" + SID + "'",
  147. conn);
  148. cmd.ExecuteNonQuery();
  149. cmd.Dispose();
  150. ShowMessage("Student Data Delete Successfully......!");
  151. GridViewStudent.EditIndex = -1;
  152. BindGridView();
  153. }
  154. catch (MySqlException ex)
  155. {
  156. ShowMessage(ex.Message);
  157. }
  158. Finally
  159. {
  160. conn.Close();
  161. }
  162. }
  163. #endregion
  164. #region student data update
  165. /// <summary>
  166. /// This code used to student data update
  167. /// </summary>
  168. /// <param name="sender"></param>
  169. /// <param name="e"></param>
  170. protected void btnUpdate_Click(object sender, EventArgs e)
  171. {
  172. Try
  173. {
  174. conn.Open();
  175. string SID = lblSID.Text;
  176. MySqlCommand cmd = new MySqlCommand("update student Set
  177. Name=@Name,Address=@Address,Mobile=@Mobile,Email=@Email where SID=@SID", conn);
  178. cmd.Parameters.AddWithValue("@Name", txtName.Text);
  179. cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
  180. cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
  181. cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
  182. cmd.Parameters.AddWithValue("SID",SID);
  183. cmd.ExecuteNonQuery();
  184. cmd.Dispose();
  185. ShowMessage("Student Data update Successfully......!");
  186. GridViewStudent.EditIndex = -1;
  187. BindGridView(); btnUpdate.Visible = false;
  188. }
  189. catch (MySqlException ex)
  190. {
  191. ShowMessage(ex.Message);
  192. }
  193. Finally
  194. {
  195. conn.Close();
  196. }
  197. }
  198. #endregion
  199. #region textbox clear
  200. protected void btnCancel_Click(object sender, EventArgs e)
  201. {
  202. clear();
  203. }
  204. #endregion
  205. }
  206. }

Now run the page, it will look like the following.



Now, enter the student data insert and Grid view Show Data. Message box “Registered successfully”.



Now, select the Student then show the data TextBox and update the data shown in the Message box “Student Data update successfully”.



Now, delete the Student data shown in the Message box “Student Data Delete Successfully”.



I hope this article is useful. If you have any other questions then please provide your comments below.