Thursday, May 3

FETCHING DATA FROM DATABASE AND POPULATING FIELDS IN THE FORM USING LINQ TO SQL


STEP 1: Setting up the GUI

To get started, add a new WebForm to your application and set up the GUI. Again just for the simplicity of this demo,I just set up the GUI like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LINQ to SQL Demo Part 2</title>
    <style type="text/css">
        .style1{width400px;}
        .style1 td {width:200px;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DropDownList ID="DropDownListCustomerID" runat="server"
            AutoPostBack="true"
           onselectedindexchanged="DropDownListCustomerID_SelectedIndexChanged">
        </asp:DropDownList>
        <br />
        <table class="style1">
            <tr>
                <td>Company Name</td>
                <td><asp:TextBox ID="TextBoxCompanyName" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Contact Name</td>
                <td><asp:TextBox ID="TextBoxContactName" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Contact Title</td>
                <td><asp:TextBox ID="TextBoxContactTitle" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><asp:TextBox ID="TextBoxAddress" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>City</td>
                <td><asp:TextBox ID="TextBoxCity" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Region</td>
                <td><asp:TextBox ID="TextBoxRegion" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Postal Code</td>
                <td><asp:TextBox ID="TextBoxPostalCode" runat="server"ReadOnly="true"/></td>
            </tr>
            <tr>
                <td>Country</td>
                <td><asp:TextBox ID="TextBoxCountry" runat="server"ReadOnly="true"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

If you notice, I set the ReadOnly attribute of each TextBox to True; this is because we don’t need users to edit the fields in the form once the TextBox is filled with data.

STEP 2: Populating the DropDownList with the list of Customers.

Now on our code behind page let’s go ahead and create the method for fetching the list of customers. Here’s the code block below:

    private List<Customer> GetCustomers(){
        using (NorthwindDataContext context = new NorthwindDataContext()){
            return (from c in context.Customers select c).ToList();
        }
    }

The code above is the LINQ syntax for querying data. It basically query the Customers object that is generated from the DataContext and then fetch the results. 

Since we are done creating the method for fetching the list of customers then we can simply call that method and populate the DropDownList with the results. Typically we do this at Page_Load event within Not IsPostBack block like below:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {
            DropDownListCustomerID.DataSource = GetCustomers();
            DropDownListCustomerID.DataTextField = "ContactName";
            DropDownListCustomerID.DataValueField = "CustomerID";
            DropDownListCustomerID.DataBind();
        }
    }

As you can see the code above is very straight forward and self explanatory. Running the code above will display something like below:

 

Let’s proceed and continue with the next Step.

STEP 3: Populating the form with Customer’s Information

The next step is we are going to populate the form with the customer information based on the CustomerID selected from the DropDownList.

Note: Since the form will be populated based on the selected item from the DropDownList then you’ll need to set up the AutoPostBack attribute to TRUE in the DropDownList so that the SelectedIndexChanged event will fire up.

Here’s the code block below for fetching the customer information based on customer ID:
    private List<Customer> GetCustomerInfo(string customerID) {
        using (NorthwindDataContext context = new NorthwindDataContext()){
            return(from c in context.Customers
                   where c.CustomerID == customerID
                   select c).ToList();
        }
    }

The code above is the LINQ syntax for querying data. As you can see we created a new instance of the DataContext and query the Customers object based on the parameter we passed on the GetCustomerInfo() method. Once we invoke the LINQ ToList() function, this LINQ query will issue a parameterize SQL query to the database in which the SQL Server can understand and then bring back the results to the DataContext.

One of the cool things about L2S is we don’t need to worry about how the query is being constructed because L2S will take care of that for you including mapping of the data types from your table columns, mapping relationships between tables, etcetera, etcetera and etcetera. Always keep in mind that L2S is an ORM (Object Relational Mapper) and so we don’t need to deal directly with databases, tables and columns but instead we deal with the objects that is in the DataContext and query the data against it using LINQ syntax.

STEP 4: Populating the Forms with Data

The next step is to populate our form with data based on the selected value from the DropDownList. To do this, we can simply call the method GetCustomerInfo() at the SelectedIndexChanged event of DropDownList like below:

    protected void DropDownListCustomerID_SelectedIndexChanged(object sender,EventArgs e) {
        var customerInfo = GetCustomerInfo(DropDownListCustomerID.SelectedValue);
        TextBoxCompanyName.Text = customerInfo[0].CompanyName;
        TextBoxContactName.Text = customerInfo[0].ContactName;
        TextBoxContactTitle.Text = customerInfo[0].ContactTitle;
        TextBoxAddress.Text = customerInfo[0].Address;
        TextBoxCity.Text = customerInfo[0].City;
        TextBoxRegion.Text = customerInfo[0].Region;
        TextBoxPostalCode.Text = customerInfo[0].PostalCode;
        TextBoxCountry.Text = customerInfo[0].Country;
    }

The code above calls the method GetCustomerInfo() and pass the selected value of the DropDownList as a parameter to that method. We then store it a customerInfo implicit typed variable and assign each TextBox with the corresponding data returned from the query.

When you run the code above and select an item in the DropDownList, you will see that the textbox fields will be populated with data based from what you have selected in the DropDownList.


Thanks Shibashish Mohanty

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty