CSharp Finding Particular Row In Dataset – ADO.Net Database

<%@ Page Language="C#" ClassName="Default" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">    void Page_Load(Object sender, EventArgs e)
    {
        SqlConnection  sqlConnection;
        SqlDataAdapter sqlDataAdapter;
        SqlCommand     sqlCommand;
        DataSet       dataSet;
        DataTable      dataTable;
 
    if (IsPostBack) {
      try{
          sqlConnection = new SqlConnection( "Integrated Security=yes;Initial Catalog=Northwind;Data Source=(local)" );
        sqlCommand = new SqlCommand( "Select * From Customers", sqlConnection );
 
        sqlDataAdapter = new SqlDataAdapter( sqlCommand );
        dataSet = new DataSet();
 
        sqlDataAdapter.Fill( dataSet, "Customers" );
 
        DataColumn [] pkColumn = new DataColumn[1];
        pkColumn[0] = dataSet.Tables[0].Columns["CustomerID"];        dataSet.Tables[0].PrimaryKey = pkColumn;        DataRow rowFound = dataSet.Tables[0].Rows.Find(customerIdTextBox.Text);
 
        if (rowFound == null)
        {
          msgLabel.Text = "The Customer ID entered was not found.";
        }
        else
        {
          StringBuilder stringBuilder = new StringBuilder("Contact ");          stringBuilder.Append(rowFound["ContactName"].ToString());
          stringBuilder.Append(", ");
          stringBuilder.Append(rowFound["ContactTitle"].ToString());
          stringBuilder.Append(" at ");
          stringBuilder.Append(rowFound["CompanyName"].ToString());          msgLabel.Text = stringBuilder.ToString();
        }
      }
      catch( Exception exception )
      {
        msgLabel.Text = exception.ToString();
      }
    }
    }</script>
<html>
  <head>
    <title>Finding a Particular Row in a DataSet</title>
  </head>
  <body>
    <form id="form1" method="post" runat="server">
      <asp:label id="customerIdLabel" runat="server">Customer ID:</asp:label>
      <asp:textbox id="customerIdTextBox" runat="server"></asp:textbox>
      <asp:button id="findButton" runat="server" Text="Find"></asp:button><br />
      <asp:label id="msgLabel" runat="server" ></asp:label></form>
  </body>
</html>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.