CRUD


Figure 1: Database

Sample Database

Let’s create a sample database named ‘SampleDB’ with SQL Management Studio. Using the ‘SampleDB’ now create a Table and name it ‘tblCustomer’.

Script

  1. CREATETABLE [dbo].[tblCustomer]
  2. (
  3. [CustID] [bigint] NOTNULL,
  4. [CustName] [nvarchar](50)NULL,
  5. [CustEmail] [nvarchar](50)NOTNULL,
  6. [CustAddress] [nvarchar](256)NULL,
  7. [CustContact] [nvarchar](50)NULL,
  8. CONSTRAINT [PK_tblCustomer] PRIMARYKEYCLUSTERED
  9. (
  10. [CustID] ASC,
  11. [CustEmail] ASC
  12. )WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
  13. )ON [PRIMARY]
  14. GO
Stored Procedure

Now in the following step we will perform CRUD operations with stored procedure:
  1. First we will create a stored procedure (SP) to RETRIVE record from Customer table.
  2. Now we will create a stored procedure( SP) to INSERT record into Customer table.
  3. Now we will create another procedure (SP) to UPDATE existing data in our Customer table.
  4. The last step we will create a stored procedure to DELETE existing record from customer table.

Stored Procedure to RETRIVE Record

  1. ALTERPROCEDURE [dbo].[READ_CUSTOMER]
  2. -- Add the parameters for the stored procedure here
  3. @PageNo INT
  4. ,@RowCountPerPage INT
  5. ,@IsPaging INT
  6. AS
  7. BEGIN
  8. -- SET NOCOUNT ON added to prevent extra result sets from
  9. SETNOCOUNTON;
  10. -- Select statements for procedure here
  11. IF(@IsPaging = 0)
  12. BEGIN
  13. SELECTtop(@RowCountPerPage)*FROM [dbo].[tblCustomer]
  14. ORDERBY CustID DESC
  15. END
  16. IF(@IsPaging = 1)
  17. BEGIN
  18. DECLARE @SkipRow INT
  19. SET @SkipRow =(@PageNo - 1)* @RowCountPerPage
  20. SELECT*FROM [dbo].[tblCustomer]
  21. ORDERBY CustID DESC
  22. OFFSET @SkipRow ROWSFETCHNEXT @RowCountPerPage ROWS ONLY
  23. END
  24. END
Stored Procedure to INSERT Record
  1. ALTERPROCEDURE [dbo].[CREATE_CUSTOMER]
  2. -- Add the parameters for the stored procedure here
  3. (
  4. @CustName NVarchar(50)
  5. ,@CustEmail NVarchar(50)
  6. ,@CustAddress NVarchar(256)
  7. ,@CustContact NVarchar(50)
  8. )
  9. AS
  10. BEGIN
  11. ---- SET NOCOUNT ON added to prevent extra result sets from
  12. SETNOCOUNTON;
  13. ---- Try Catch--
  14. BEGINTRY
  15. BEGINTRANSACTION
  16. DECLARE @CustID Bigint
  17. SET @CustID =isnull(((SELECTmax(CustID)FROM [dbo].[tblCustomer])+1),'1')
  18. -- Insert statements for procedure here
  19. INSERTINTO [dbo].[tblCustomer]([CustID],[CustName],[CustEmail],[CustAddress],[CustContact])
  20. VALUES(@CustID,@CustName,@CustEmail,@CustAddress,@CustContact)
  21. SELECT 1
  22. COMMITTRANSACTION
  23. ENDTRY
  24. BEGINCATCH
  25. DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;
  26. SELECT @ErrorMessage =ERROR_MESSAGE(),@ErrorSeverity =ERROR_SEVERITY(),@ErrorState =ERROR_STATE();
  27. RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);
  28. ROLLBACKTRANSACTION
  29. ENDCATCH
  30. END
Stored Procedure to UPDATE Record
  1. ALTERPROCEDURE [dbo].[UPDATE_CUSTOMER]
  2. -- Add the parameters for the stored procedure here
  3. @CustID BIGINT
  4. ,@CustName NVarchar(50)
  5. ,@CustEmail NVarchar(50)
  6. ,@CustAddress NVarchar(256)
  7. ,@CustContact NVarchar(50)
  8. AS
  9. BEGIN
  10. ---- SET NOCOUNT ON added to prevent extra result sets from
  11. SETNOCOUNTON;
  12. ---- Try Catch--
  13. BEGINTRY
  14. BEGINTRANSACTION
  15. -- Update statements for procedure here
  16. UPDATE [dbo].[tblCustomer]
  17. SET [CustName] = @CustName,
  18. [CustAddress] = @CustAddress,
  19. [CustContact] = @CustContact
  20. WHERE [CustID] = @CustID AND [CustEmail] = @CustEmail
  21. SELECT 1
  22. COMMITTRANSACTION
  23. ENDTRY
  24. BEGINCATCH
  25. DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;
  26. SELECT @ErrorMessage =ERROR_MESSAGE(),@ErrorSeverity =ERROR_SEVERITY(),@ErrorState =ERROR_STATE();
  27. RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);
  28. ROLLBACKTRANSACTION
  29. ENDCATCH
  30. END
Stored Procedure to DELETE Record
  1. ALTERPROCEDURE [dbo].[DELETE_CUSTOMER]
  2. -- Add the parameters for the stored procedure here
  3. @CustID BIGINT
  4. AS
  5. BEGIN
  6. ---- SET NOCOUNT ON added to prevent extra result sets from
  7. SETNOCOUNTON;
  8. ---- Try Catch--
  9. BEGINTRY
  10. BEGINTRANSACTION
  11. -- Delete statements for procedure here
  12. DELETE [dbo].[tblCustomer]
  13. WHERE [CustID] = @CustID
  14. SELECT 1
  15. COMMITTRANSACTION
  16. ENDTRY
  17. BEGINCATCH
  18. DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;
  19. SELECT @ErrorMessage =ERROR_MESSAGE(),@ErrorSeverity =ERROR_SEVERITY(),@ErrorState =ERROR_STATE();
  20. RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);
  21. ROLLBACKTRANSACTION
  22. ENDCATCH
  23. END
Stored Procedure to VIEW Single Record Details
  1. ALTERPROCEDURE [dbo].[VIEW_CUSTOMER]
  2. -- Add the parameters for the stored procedure here
  3. @CustID BIGINT
  4. AS
  5. BEGIN
  6. -- SET NOCOUNT ON added to prevent extra result sets from
  7. SETNOCOUNTON;
  8. -- Select statements for procedure here
  9. SELECT*FROM [dbo].[tblCustomer]
  10. WHERE [CustID] = @CustID
  11. END
Let’s Start

Open Visual Studio 2015, Click File, New, then Project. In this window give a name to the project and solution.



Figure 2: Open VS

Click OK and another window will appear with project template; choose Web API.



Figure 3: Click Another

Click OK and the visual studio will create and load a new ASP.NET application template.

In this app we are going to apply CRUD operation on a single table named Customer. To do first we need to create API Controller for the operations. To add a new Controller file we need to right click and an option menu will appear. After that click Add, then Controller.



Figure 4: Add

Let’s name it CustomerController. In the controller we will create action methods to perform CRUD operations:



Figure 5: Crud

API Controller for CRUD operations
  1. namespace CRUD_APi.Controllers.apiController {
  2. [RoutePrefix("api/Customer")]
  3. publicclassCustomerController: ApiController {
  4. // GET: api/Customer?RowCount=5
  5. [HttpGet]
  6. publicIEnumerable < tblCustomer > GetCustomers(int pageSize) {
  7. try {
  8. int pageNumber = 0;
  9. int IsPaging = 0;
  10. CrudDataService objCrd = newCrudDataService();
  11. List < tblCustomer > modelCust = objCrd.GetCustomerList(pageNumber, pageSize, IsPaging);
  12. return modelCust;
  13. } catch {
  14. throw;
  15. }
  16. }
  17. // GET: api/Customer/InfinitScroll
  18. [HttpGet]
  19. publicIEnumerable < tblCustomer > GetCustomerScroll(int pageNumber, int pageSize) {
  20. try {
  21. int IsPaging = 1;
  22. CrudDataService objCrd = newCrudDataService();
  23. List < tblCustomer > modelCust = objCrd.GetCustomerList(pageNumber, pageSize, IsPaging);
  24. return modelCust;
  25. } catch (Exception ex) {
  26. throw ex;
  27. }
  28. }
  29. // GET: api/Customer/Create
  30. [HttpPost]
  31. [ResponseType(typeof(tblCustomer))]
  32. publicstring Create(tblCustomer objCust) {
  33. try {
  34. CrudDataService objCrd = newCrudDataService();
  35. Int32 message = 0;
  36. if ((objCust.CustName != null) && (objCust.CustEmail != null)) message = objCrd.InsertCustomer(objCust);
  37. else message = -1;
  38. return message.ToString();
  39. } catch {
  40. throw;
  41. }
  42. }
  43. // GET: api/Customer/Get
  44. [HttpGet]
  45. publictblCustomer GetCustomer(long ? id) {
  46. try {
  47. CrudDataService objCrd = newCrudDataService();
  48. tblCustomer modelCust = objCrd.GetCustomerDetails(id);
  49. return modelCust;
  50. } catch {
  51. throw;
  52. }
  53. }
  54. // GET: api/Customer/Edit
  55. [HttpPost]
  56. [ResponseType(typeof(tblCustomer))]
  57. publicstring Edit(tblCustomer objCust) {
  58. try {
  59. CrudDataService objCrd = newCrudDataService();
  60. Int32 message = 0;
  61. message = objCrd.UpdateCustomer(objCust);
  62. return message.ToString();
  63. } catch {
  64. throw;
  65. }
  66. }
  67. // GET: api/Customer/Delete
  68. [HttpDelete]
  69. publicstring Delete(long ? id) {
  70. try {
  71. CrudDataService objCrd = newCrudDataService();
  72. Int32 message = 0;
  73. message = objCrd.DeleteCustomer(id);
  74. return message.ToString();
  75. } catch {
  76. throw;
  77. }
  78. }
  79. }
  80. }
Data Service

As we know earlier that we will use ADO.NET and Stored Procedure and to connect the database we need to modify our config file to add Connection String for database connection.
  1. <connectionStrings>
  2. <addnameaddname="dbConn"connectionString="Data source=DESKTOP-4L9DM2J; Initial Catalog=SampleDB; User Id=sa; Password=sa@123"providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
Now we need to create another class to use connection string and open our database connection, let’s name it dbConnector.
  1. // Database Connection
  2. publicclassdbConnector
  3. {
  4. privateSqlConnection SqlConn = null;
  5. publicSqlConnection GetConnection
  6. {
  7. get { return SqlConn; }
  8. set { SqlConn = value; }
  9. }
  10. public dbConnector()
  11. {
  12. string ConnectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
  13. SqlConn = newSqlConnection(ConnectionString);
  14. }
  15. }
To perform CRUD operations we will create a separate class called CrudDataService. In this class we have five methods that will interact with the database to perform CRUD operations.
  1. // Database Service
  2. namespace CRUD_DataService {
  3. // Database Service
  4. publicclassCrudDataService {
  5. publicList < tblCustomer > GetCustomerList(int PageNo, int RowCountPerPage, int IsPaging) {
  6. dbConnector objConn = newdbConnector();
  7. SqlConnection Conn = objConn.GetConnection;
  8. Conn.Open();
  9. try {
  10. List < tblCustomer > _listCustomer = newList < tblCustomer > ();
  11. if (Conn.State != System.Data.ConnectionState.Open) Conn.Open();
  12. SqlCommand objCommand = newSqlCommand("READ_CUSTOMER", Conn);
  13. objCommand.CommandType = CommandType.StoredProcedure;
  14. objCommand.Parameters.AddWithValue("@PageNo", PageNo);
  15. objCommand.Parameters.AddWithValue("@RowCountPerPage", RowCountPerPage);
  16. objCommand.Parameters.AddWithValue("@IsPaging", IsPaging);
  17. SqlDataReader _Reader = objCommand.ExecuteReader();
  18. while (_Reader.Read()) {
  19. tblCustomer objCust = newtblCustomer();
  20. objCust.CustID = Convert.ToInt32(_Reader["CustID"]);
  21. objCust.CustName = _Reader["CustName"].ToString();
  22. objCust.CustEmail = _Reader["CustEmail"].ToString();
  23. objCust.CustAddress = _Reader["CustAddress"].ToString();
  24. objCust.CustContact = _Reader["CustContact"].ToString();
  25. _listCustomer.Add(objCust);
  26. }
  27. return _listCustomer;
  28. } catch {
  29. throw;
  30. } finally {
  31. if (Conn != null) {
  32. if (Conn.State == ConnectionState.Open) {
  33. Conn.Close();
  34. Conn.Dispose();
  35. }
  36. }
  37. }
  38. }
  39. publictblCustomer GetCustomerDetails(long ? id) {
  40. dbConnector objConn = newdbConnector();
  41. SqlConnection Conn = objConn.GetConnection;
  42. Conn.Open();
  43. try {
  44. tblCustomer objCust = newtblCustomer();
  45. if (Conn.State != System.Data.ConnectionState.Open) Conn.Open();
  46. SqlCommand objCommand = newSqlCommand("VIEW_CUSTOMER", Conn);
  47. objCommand.CommandType = CommandType.StoredProcedure;
  48. objCommand.Parameters.AddWithValue("@CustID", id);
  49. SqlDataReader _Reader = objCommand.ExecuteReader();
  50. while (_Reader.Read()) {
  51. objCust.CustID = Convert.ToInt32(_Reader["CustID"]);
  52. objCust.CustName = _Reader["CustName"].ToString();
  53. objCust.CustEmail = _Reader["CustEmail"].ToString();
  54. objCust.CustAddress = _Reader["CustAddress"].ToString();
  55. objCust.CustContact = _Reader["CustContact"].ToString();
  56. }
  57. return objCust;
  58. } catch {
  59. throw;
  60. } finally {
  61. if (Conn != null) {
  62. if (Conn.State == ConnectionState.Open) {
  63. Conn.Close();
  64. Conn.Dispose();
  65. }
  66. }
  67. }
  68. }
  69. publicInt32 InsertCustomer(tblCustomer objCust) {
  70. dbConnector objConn = newdbConnector();
  71. SqlConnection Conn = objConn.GetConnection;
  72. Conn.Open();
  73. int result = 0;
  74. try {
  75. if (Conn.State != System.Data.ConnectionState.Open) Conn.Open();
  76. SqlCommand objCommand = newSqlCommand("CREATE_CUSTOMER", Conn);
  77. objCommand.CommandType = CommandType.StoredProcedure;
  78. objCommand.Parameters.AddWithValue("@CustName", objCust.CustName);
  79. objCommand.Parameters.AddWithValue("@CustEmail", objCust.CustEmail);
  80. objCommand.Parameters.AddWithValue("@CustAddress", objCust.CustAddress);
  81. objCommand.Parameters.AddWithValue("@CustContact", objCust.CustContact);
  82. result = Convert.ToInt32(objCommand.ExecuteScalar());
  83. if (result > 0) {
  84. return result;
  85. } else {
  86. return 0;
  87. }
  88. } catch {
  89. throw;
  90. } finally {
  91. if (Conn != null) {
  92. if (Conn.State == ConnectionState.Open) {
  93. Conn.Close();
  94. Conn.Dispose();
  95. }
  96. }
  97. }
  98. }
  99. publicInt32 UpdateCustomer(tblCustomer objCust) {
  100. dbConnector objConn = newdbConnector();
  101. SqlConnection Conn = objConn.GetConnection;
  102. Conn.Open();
  103. int result = 0;
  104. try {
  105. if (Conn.State != System.Data.ConnectionState.Open) Conn.Open();
  106. SqlCommand objCommand = newSqlCommand("UPDATE_CUSTOMER", Conn);
  107. objCommand.CommandType = CommandType.StoredProcedure;
  108. objCommand.Parameters.AddWithValue("@CustID", objCust.CustID);
  109. objCommand.Parameters.AddWithValue("@CustName", objCust.CustName);
  110. objCommand.Parameters.AddWithValue("@CustEmail", objCust.CustEmail);
  111. objCommand.Parameters.AddWithValue("@CustAddress", objCust.CustAddress);
  112. objCommand.Parameters.AddWithValue("@CustContact", objCust.CustContact);
  113. result = Convert.ToInt32(objCommand.ExecuteScalar());
  114. if (result > 0) {
  115. return result;
  116. } else {
  117. return 0;
  118. }
  119. } catch {
  120. throw;
  121. } finally {
  122. if (Conn != null) {
  123. if (Conn.State == ConnectionState.Open) {
  124. Conn.Close();
  125. Conn.Dispose();
  126. }
  127. }
  128. }
  129. }
  130. publicInt32 DeleteCustomer(long ? id) {
  131. dbConnector objConn = newdbConnector();
  132. SqlConnection Conn = objConn.GetConnection;
  133. Conn.Open();
  134. int result = 0;
  135. try {
  136. if (Conn.State != System.Data.ConnectionState.Open) Conn.Open();
  137. SqlCommand objCommand = newSqlCommand("DELETE_CUSTOMER", Conn);
  138. objCommand.CommandType = CommandType.StoredProcedure;
  139. objCommand.Parameters.AddWithValue("@CustID", id);
  140. result = Convert.ToInt32(objCommand.ExecuteScalar());
  141. if (result > 0) {
  142. return result;
  143. } else {
  144. return 0;
  145. }
  146. } catch {
  147. throw;
  148. } finally {
  149. if (Conn != null) {
  150. if (Conn.State == ConnectionState.Open) {
  151. Conn.Close();
  152. Conn.Dispose();
  153. }
  154. }
  155. }
  156. }
  157. }
  158. }
Publish the Site in IIS



Figure 6: IIS

Let’s assign a port to access, In this case the site base url is: http://localhost:8081/.



Figure 7: Localhost

Let’s Create Windows Form Application

Open Visual Studio 2015, Click File, New, then Project. In this window give a name to the project and solution. This time we will create a Windows Form Application.



Figure 8: VS2015

In our new application let’s create a new Form and name it CRUDForm.cs



Figure 9: Crud Form

Our new form will look like the following screen:



Figure 10: new

In CRUD form we have a data grid which will load all data from the database through API controller.

Form Submission Code
  1. namespace CRUD_WF
  2. {
  3. publicpartialclassCRUDForm : Form
  4. {
  5. privateint pageNumber = 1;
  6. privateint pageSize = 0;
  7. privatestring baseUrl = string.Empty;
  8. privatestring url = string.Empty;
  9. public CRUDForm()
  10. {
  11. InitializeComponent();
  12. baseUrl = txtUrl.Text.ToString().Trim();
  13. pageSize = 5;
  14. url = baseUrl + "api/Customer?pageSize=" + pageSize;
  15. }
  16. privatevoid CRUDForm_Load(object sender, EventArgs e)
  17. {
  18. GetCustomer_(url);
  19. }
  20. privateasyncvoid GetCustomer_(string url)
  21. {
  22. try
  23. {
  24. using (var objClient = newHttpClient())
  25. {
  26. using (var response = await objClient.GetAsync(url))
  27. {
  28. if (response.IsSuccessStatusCode)
  29. {
  30. var productJsonString = await response.Content.ReadAsStringAsync();
  31. dgList.DataSource = JsonConvert.DeserializeObject<tblCustomer[]>(productJsonString).ToList();
  32. }
  33. }
  34. }
  35. }
  36. catch
  37. {
  38. pageSize = 5; pageNumber = 1;
  39. MessageBox.Show("Invalid URL!!");
  40. }
  41. }
  42. privatevoid btnSubmit_Click(object sender, EventArgs e)
  43. {
  44. if (btnSubmit.Text != "Update")
  45. {
  46. CreateCustomer();
  47. }
  48. else
  49. {
  50. if (lblCustID.Text == "")
  51. {
  52. MessageBox.Show("Please Select a Customer to Edit");
  53. }
  54. else
  55. {
  56. EditCustomer();
  57. }
  58. }
  59. }
  60. privateasyncvoid CreateCustomer()
  61. {
  62. try
  63. {
  64. string InsertUrl = baseUrl + "api/Customer/Create";
  65. tblCustomer objCust = newtblCustomer();
  66. objCust.CustName = txtCustName.Text.ToString();
  67. objCust.CustEmail = txtCustEmail.Text.ToString();
  68. objCust.CustAddress = txtCustAddress.Text.ToString();
  69. objCust.CustContact = txtCustContact.Text.ToString();
  70. if ((objCust != null) && (objCust.CustEmail != ""))
  71. {
  72. using (var objClient = newHttpClient())
  73. {
  74. string contentType = "application/json";
  75. var serializedCustomer = JsonConvert.SerializeObject(objCust);
  76. var content = newStringContent(serializedCustomer, Encoding.UTF8, contentType);
  77. var result = await objClient.PostAsync(InsertUrl, content);
  78. GetCustomer_(url);
  79. Clear();
  80. }
  81. }
  82. else
  83. {
  84. MessageBox.Show("Email Id is Must!");
  85. }
  86. }
  87. catch
  88. {
  89. MessageBox.Show("Invalid Customer!!");
  90. }
  91. }
  92. privateasyncvoid EditCustomer()
  93. {
  94. try
  95. {
  96. string EditUrl = baseUrl + "api/Customer/Edit";
  97. tblCustomer objCust = newtblCustomer();
  98. objCust.CustID = Convert.ToInt32(lblCustID.Text);
  99. objCust.CustName = txtCustName.Text.ToString();
  100. objCust.CustEmail = txtCustEmail.Text.ToString();
  101. objCust.CustAddress = txtCustAddress.Text.ToString();
  102. objCust.CustContact = txtCustContact.Text.ToString();
  103. if ((objCust != null) && (objCust.CustEmail != ""))
  104. {
  105. using (var objClient = newHttpClient())
  106. {
  107. string contentType = "application/json";
  108. var serializedCustomer = JsonConvert.SerializeObject(objCust);
  109. var content = newStringContent(serializedCustomer, Encoding.UTF8, contentType);
  110. var result = await objClient.PostAsync(EditUrl, content);
  111. GetCustomer_(url);
  112. }
  113. }
  114. else
  115. {
  116. MessageBox.Show("Email Id is Must!");
  117. }
  118. }
  119. catch
  120. {
  121. MessageBox.Show("Invalid Customer!!");
  122. }
  123. }
  124. privatevoid btnDelete_Click(object sender, EventArgs e)
  125. {
  126. try
  127. {
  128. if (lblCustID.Text == "")
  129. {
  130. MessageBox.Show("Please Select a Customer to Delete");
  131. }
  132. else
  133. {
  134. DialogResult result = MessageBox.Show("You are about to delete " + txtCustName.Text + " permanently. Are you sure you want to delete this record?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
  135. if (result.Equals(DialogResult.OK))
  136. {
  137. long CustID = Convert.ToInt64(lblCustID.Text);
  138. DeleteCustomer(CustID);
  139. }
  140. }
  141. }
  142. catch
  143. {
  144. MessageBox.Show("Invalid Customer!!");
  145. }
  146. }
  147. privateasyncvoid DeleteCustomer(long? id)
  148. {
  149. try
  150. {
  151. string DeleteUrl = baseUrl + "api/Customer/Delete";
  152. using (var objClient = newHttpClient())
  153. {
  154. var result = await objClient.DeleteAsync(String.Format("{0}/{1}", DeleteUrl, id));
  155. }
  156. GetCustomer_(url);
  157. }
  158. catch
  159. {
  160. MessageBox.Show("Invalid Customer!!");
  161. }
  162. }
  163. privatevoid btnNew_Click(object sender, EventArgs e)
  164. {
  165. Clear();
  166. }
  167. privatevoid btnReset_Click(object sender, EventArgs e)
  168. {
  169. Clear();
  170. }
  171. privatevoid Clear()
  172. {
  173. lblCustID.Text = "";
  174. txtCustName.Text = "";
  175. txtCustEmail.Text = "";
  176. txtCustAddress.Text = "";
  177. txtCustContact.Text = "";
  178. btnSubmit.Text = "Submit";
  179. txtCustEmail.ReadOnly = false;
  180. }
  181. privatevoid txtUrl_TextChanged(object sender, EventArgs e)
  182. {
  183. try
  184. {
  185. baseUrl = txtUrl.Text.ToString().Trim();
  186. }
  187. catch
  188. {
  189. MessageBox.Show("Invalid Approach!!");
  190. }
  191. }
  192. privatevoid btnNext_Click(object sender, EventArgs e)
  193. {
  194. try
  195. {
  196. if (pageNumber == 0)
  197. pageNumber = 1;
  198. pageSize = 5; pageNumber++;
  199. string url = baseUrl + "api/Customer?pageNumber=" + pageNumber + "&pageSize=" + pageSize;
  200. GetCustomer_(url);
  201. btnReload.Text = "Page View: " + pageNumber.ToString() + "/Reload..";
  202. }
  203. catch
  204. {
  205. MessageBox.Show("Invalid Approach!!");
  206. }
  207. }
  208. privatevoid btnPrev_Click(object sender, EventArgs e)
  209. {
  210. try
  211. {
  212. pageSize = 5; pageNumber--;
  213. if (pageNumber == 0)
  214. pageNumber = pageNumber + 1;
  215. string url = baseUrl + "api/Customer?pageNumber=" + pageNumber + "&pageSize=" + pageSize;
  216. GetCustomer_(url);
  217. btnReload.Text = "Page View: " + pageNumber.ToString() + "/Reload..";
  218. }
  219. catch
  220. {
  221. MessageBox.Show("Invalid Approach!!");
  222. }
  223. }
  224. privatevoid btnReload_Click(object sender, EventArgs e)
  225. {
  226. pageSize = 5;
  227. pageNumber = 1;
  228. GetCustomer_(url);
  229. btnReload.Text = "Reload..";
  230. }
  231. privatevoid dgList_SelectionChanged(object sender, EventArgs e)
  232. {
  233. try
  234. {
  235. if (dgList.SelectedCells.Count > 0)
  236. {
  237. int selectedrowindex = dgList.SelectedCells[0].RowIndex;
  238. DataGridViewRow selectedRow = dgList.Rows[selectedrowindex];
  239. lblCustID.Text = Convert.ToString(selectedRow.Cells[0].Value);
  240. txtCustName.Text = Convert.ToString(selectedRow.Cells[1].Value);
  241. txtCustEmail.Text = Convert.ToString(selectedRow.Cells[2].Value);
  242. txtCustAddress.Text = Convert.ToString(selectedRow.Cells[3].Value);
  243. txtCustContact.Text = Convert.ToString(selectedRow.Cells[4].Value);
  244. btnSubmit.Text = "Update";
  245. txtCustEmail.ReadOnly = true;
  246. }
  247. }
  248. catch
  249. {
  250. MessageBox.Show("Invalid Customer!!");
  251. }
  252. }
  253. }
  254. }
Desktop Application

In this stage we need to input the HTTP URL to perform CRUD Operation through API controller.



Figure 11: Web App

Web Application



Figure 12: Output

OUTPUT

Finally displaying data in both Web & Desktop Application at the same time using Web API.
Hope this will help someone. Thanks!