CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
ListView Control with LINQ to SQL Class– Part 2

By Satheesh babu
Posted On Oct 06,2008
Article Rating:
Be first to rate
this article.
No of Comments: 4
Category: ASP.Net 3.5
Print this article.

ListView Control with LINQ to SQL Class– Part 2

 

In Part1, we have seen the basics of LINQ to SQL classes and the tools (LINQ to SQL designer) for generating LINQ to SQL class in Visual Studio 2008. Also, we have binded ListView control with LINQDatasource control and provided edit, update, delete and insert feature using LINQDatasource control. In Part 2, we will understand how the same tasks can be done without LinqDataSource control.  We will use the same Employee table to understand the custom databinding using LINQ.

Refer Part1 to know more about creating LINQ to SQL classes. We will use the same datamodel which we used in Part 1 in this article too.

 

In Part 1, we have used LinqDataSource control to bind the ListView control. In Part 2, we will bind the ListView Control without LinqDataSource control using LINQ to SQL classes and provide edit, update and delete functionality to it by writing custom LINQ query.

 

Steps

1.      Design the ListView control with LayoutTemplate, ItemTemplate, InsertItemTemplate, and EditItemTemplate. Refer the below code. We will have a dropdownlist for binding the list of available departments in InsertItemTemplate and EditItemTemplate.

 

<asp:ListView ID="lvEmployee" runat="server"         

InsertItemPosition="LastItem" onitemcanceling="lvEmployee_ItemCanceling"

            onitemediting="lvEmployee_ItemEditing"

             onitemupdating="lvEmployee_ItemUpdating"

             onitemdeleting="lvEmployee_ItemDeleting"

             oniteminserting="lvEmployee_ItemInserting">

        <LayoutTemplate>

                <table id="Table1" runat="server">

                    <tr id="Tr1" runat="server">

                        <td id="Td1" runat="server">

                            <table ID="itemPlaceholderContainer" runat="server" border="0" style="">

                                <tr id="Tr2" runat="server" style="">

                                    <th id="Th1" runat="server">

                                    </th>

                                    <th id="Th2" runat="server">

                                        EmpID</th>

                                    <th id="Th3" runat="server">

                                        EmpName</th>

                                    <th id="Th4" runat="server">

                                        Department</th>

                                    <th id="Th5" runat="server">

                                        Age</th>

                                    <th id="Th6" runat="server">

                                        Address</th>

                                </tr>

                                <tr ID="itemPlaceholder" runat="server">

                                </tr>

                            </table>

                        </td>

                    </tr>

                    <tr id="Tr3" runat="server">

                        <td id="Td2" runat="server" style="">

                        </td>

                    </tr>

                </table>

            </LayoutTemplate>

            <ItemTemplate>

        <tr style="">

                    <td>

                        <asp:Button ID="DeleteButton" runat="server" CommandName="Delete"

                            Text="Delete" />

                        <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />

                    </td>

                    <td>

                        <asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("EmpID") %>' />

                    </td>

                    <td>

                        <asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>' />

                    </td>

                    <td>

                        <asp:Label ID="DepartmentLabel" runat="server"

                            Text='<%# Eval("Department.DepartmentName") %>' />

                    </td>

                    <td>

                        <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />

                    </td>

                    <td>

                        <asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />

                    </td>

                </tr>

            </ItemTemplate>

 <EditItemTemplate>

                <tr style="">

                    <td>

                        <asp:Button ID="UpdateButton" runat="server" CommandName="Update"

                            Text="Update" />

                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

                            Text="Cancel" />

                    </td>

                    <td>

                        <asp:Label ID="EmpIDLabel1" runat="server" Text='<%# Eval("EmpID") %>' />

                    </td>

                    <td>

                        <asp:TextBox ID="EmpNameTextBox" runat="server" Text='<%# Bind("EmpName") %>' />

                    </td>

                    <td>

                       <asp:DropDownList ID="DropDownList2" DataSource="<%# BindDept() %>"

                        SelectedValue='<%# Bind("DeptID") %>'            

                DataTextField="DepartmentName" DataValueField="DeptID" runat="server">

                </asp:DropDownList>

                    </td>

                    <td>

                        <asp:TextBox ID="AgeTextBox" runat="server" Text='<%# Bind("Age") %>' />

                    </td>

                    <td>

                        <asp:TextBox ID="AddressTextBox" runat="server" Text='<%# Bind("Address") %>' />

                    </td>

                </tr>

            </EditItemTemplate>

             <InsertItemTemplate>

                <tr style="">

                    <td>

                        <asp:Button ID="InsertButton" runat="server" CommandName="Insert"

                            Text="Insert" />

                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

                            Text="Clear" />

                    </td>

                    <td>

                        &nbsp;</td>

                    <td>

                        <asp:TextBox ID="EmpNameTextBox" runat="server"  />

                    </td>

                    <td>

                         <asp:DropDownList ID="DropDownList1"      

                DataTextField="DepartmentName" DataValueField="DeptID" runat="server">

                </asp:DropDownList>

                    </td>

                    <td>

                        <asp:TextBox ID="AgeTextBox" runat="server" />

                    </td>

                    <td>

                        <asp:TextBox ID="AddressTextBox" runat="server" />

                    </td>

                </tr>

            </InsertItemTemplate>

        </asp:ListView>

 




2.      Bind the ListView from the CodeBehind using LINQ query and LINQ to SQL classes.

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindEmp();

            BindDeptDDL();

        }

 

    }

    public void BindEmp()

    {

        EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();

 

        var LINQQuery = from emp in dbEmp.Employees

                        select emp;

        lvEmployee.DataSource = LINQQuery;

        lvEmployee.DataBind();

    }

  public void BindDeptDDL()

  {

  DropDownList ddl = lvEmployee.InsertItem.FindControl("DropDownList1") as DropDownList;

  ddl.DataSource = BindDept();

  ddl.DataBind();

  }

 

    public IEnumerable BindDept()

    {       

        EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();

        var LINQQuery = from dept in dbEmp.Departments

                        select dept;

        return LINQQuery as IEnumerable;

    }

Execute the page; you can see ListView with employee records.

ASP.Net ListView control with LINQ

3.      For ListView edit, delete and insert command to work we need to write custom LINQ query and execute it using LINQ to SQL classes. The custom LINQ queries are bolded in the below code.

  protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)

    {

        lvEmployee.EditIndex = e.NewEditIndex;

        BindEmp();

            BindDeptDDL();

    }

    protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)

    {

        lvEmployee.EditIndex = -1;

        BindEmp();

       BindDeptDDL();

    }

    protected void lvEmployee_ItemUpdating(object sender, ListViewUpdateEventArgs e)

    {

        EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();

        Label lblTemp = lvEmployee.Items[e.ItemIndex].FindControl("EmpIDLabel1") as Label;

string EmpID = "0";

       if(lblTemp !=null)

        EmpID = lblTemp.Text;

        Employee empTemp = (from emp in dbEmp.Employees

                           where emp.EmpID == int.Parse(EmpID)

                           select emp).Single();

        TextBox txtTemp = lvEmployee.Items[e.ItemIndex].FindControl("EmpNameTextBox") as TextBox;

        if (txtTemp != null)

            empTemp.EmpName = txtTemp.Text;

         DropDownList ddlTemp = lvEmployee.Items[e.ItemIndex].FindControl("DropDownList2") as DropDownList;

        if (txtTemp != null)

            empTemp.DeptID = int.Parse(ddlTemp.SelectedValue);

        txtTemp = lvEmployee.Items[e.ItemIndex].FindControl("AgeTextBox") as TextBox;

        if (txtTemp != null)

            empTemp.Age = int.Parse(txtTemp.Text);

        txtTemp = lvEmployee.Items[e.ItemIndex].FindControl("AddressTextBox") as TextBox;

        if (txtTemp != null)

            empTemp.Address = txtTemp.Text;

        dbEmp.SubmitChanges();

        lvEmployee.EditIndex = -1;

        BindEmp();

       BindDeptDDL();

    }

    protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)

    {

        EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();

        Label lblTemp = lvEmployee.Items[e.ItemIndex].FindControl("EmpIDLabel") as Label;

string EmpID = "0";

       if(lblTemp !=null)

        EmpID = lblTemp.Text;

        Employee empTemp = (from emp in dbEmp.Employees

                            where emp.EmpID == int.Parse(EmpID)

                            select emp).Single();

        dbEmp.Employees.DeleteOnSubmit(empTemp);

        dbEmp.SubmitChanges();

        BindEmp();

       BindDeptDDL();

    }

    protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)

    {

        EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();

        Employee emp = new Employee();

       TextBox txtTemp = e.Item.FindControl("EmpNameTextBox") as TextBox;

       emp.EmpName = txtTemp.Text;

       DropDownList ddlTemp = e.Item.FindControl("DropDownList1") as DropDownList;

       emp.DeptID = int.Parse(ddlTemp.SelectedValue);

       txtTemp = e.Item.FindControl("AgeTextBox") as TextBox;

       emp.Age = int.Parse(txtTemp.Text);

       txtTemp = e.Item.FindControl("AddressTextBox") as TextBox;

       emp.Address = txtTemp.Text;

 

       dbEmp.Employees.InsertOnSubmit(emp);

       dbEmp.SubmitChanges();

       BindEmp();

       BindDeptDDL();

    }  

  

Execute the page and see ListView edit/update/delete/insert in action using LINQ.

 

Note

The example discussed in this article uses lazy loading to load the related data(DepartmentName). Read the article Using DataLoadOptions to Fetch(Immediate Load) the Related Objects in LINQ to reduce the database rountrips or immediately load the related data.

Downloads

Source Code 

 

Conclusion

In Part 1, we have understood the basics of LINQ to SQL and using it asp.net by binding ListView control by using LinqDataSource controls. The Part 2 of this article helped to write custom LINQ query to do see ListView edit/update/delete/insert using LINQ to SQL classes.  Download the source attached with this article. Thanks for reading my article.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Solution
First of all THANKS a lot for writing this excellent article.

I am of the same opinion as Slabo. There are a lot of articles out there but they use LinqDataSource which is complete useless. The only way to do this is using code behind. So again thanks for an excellent article.

And also thanks for providing the source code with database. Very nice of you!

---
For all you who can't get the source code to work, this is what you have to do

string EmpID;
if (lblTemp != null)
{
EmpID = lblTemp.Text;
}
else
{
EmpID = "0";
}
---- below is the same ----
Employee empTemp = (from emp in dbEmp.Employees
where emp.EmpID == int.Parse(EmpID)
select emp).Single();

Pres F5
Voila!
THANKS!
Wow. Out of the THIRTY or so articles I've read today, this one is the only one that actually worked. Every other one left out the "lvEmployee.EditIndex = e.NewEditIndex;" part that MAKES THE EDIT POSSIBLE. Thank you very, very much for this article. I barely had any hair left.
Designer.cs file deleted when updating the diaghram
I don't have problem with creating data context files for the first time, but when I try to update table, I delete it and drag it again, the designer.cs file is deleted
A big thank you
I've just returned to .net 3.5 after a year or so, previously only dabbling with .net 2.0.

I wanted to try out listview due to the control in output, and having looked at alot of articles, this (and part 1) I've found to be clear and extremely helpful.

Thank you very much.
Simon