Labels

Showing posts with label ASP.Net - Grid Gotchas... Show all posts
Showing posts with label ASP.Net - Grid Gotchas... Show all posts

Monday, September 17, 2007

Master -Child Grid in ASP.net 1.x

Master Detail/HierarchichlaGrid in ASP.Net 1.x -








Method -1 :- (In ASPX)

DataSource=’<%# CType(Container.DataItem, DataRowView).CreateChildView(“CustOrders”) %>’

e.g

<asp:DataGrid id=”InnerGrid” runat=”server” AutoGenerateColumns=”False”

DataSource=’<%# CType(Container.DataItem, DataRowView).CreateChildView(“CustOrders”) %>’>

<Columns>

---

</Columns>

Method 2:- (In Code)

<asp:DataGrid id=”Outer Grid” runat=”server” AutoGenerateColumns=”False” DataKeyField=”CustomerID” OnItemDataBound=”BindOrdersGrid”>

Sub BindOrdersGrid(sender As Object, e As DataGridItemEventArgs)

Dim oType As ListItemType = CType(e.Item.ItemType, ListItemType)

If oType = ListItemType.Item Or oType = ListItemType.AlternatingItem Then

Dim oGrid As DataGrid = CType(e.Item.FindControl(“InnerGrid”), DataGrid)

Dim sKey As String = dgr1.DataKeys(e.Item.ItemIndex)

Dim oView, oChildView As DataView

oView = oDataSet.Tables(“Customers”).DefaultView

oView.RowFilter = “CustomerID = ‘“ & sKey.value & “‘“

oChildView = oView(0).CreateChildView(oDataSet.Relations(“CustOrders”))

oGrid.DataSource = oChildView

oGrid.DataBind()

End If

End Sub

Method 3:- (In Code)

<asp:DataGrid id=”Outer Grid” runat=”server” AutoGenerateColumns=”False” DataKeyField=”CustomerID”>

<asp:TemplateColumn HeaderText=”Customer Details”>

<ItemTemplate>

<b><%# Container.DataItem(“CompanyName”) %></b><br />

City: <%# Container.DataItem(“City”) %><br />

Country: <%# Container.DataItem(“Country”) %><br />

CustomerID: “<%# Container.DataItem(“CustomerID”) %>”

</ItemTemplate>

</asp:TemplateColumn>

<asp:TemplateColumn HeaderText=”Order History”>

<ItemTemplate>

<asp:DataGrid id=” InnerGrid” runat=”server” AutoGenerateColumns=”False”

DataSource=’<%# GetOrdersGridRows( Container.DataItem(“CustomerID”)) %>’>

</ItemTemplate>

</asp:DataGrid> // Outer Grid

Function GetOrdersGridRows(sRowKey As String) As DataView

Dim oView, oChildView As DataView

oView = oDataSet.Tables(“Customers”).DefaultView

oView.RowFilter = “CustomerID = ‘“ & sRowKey & “‘“

oChildView = oView(0).CreateChildView(oDataSet.Relations(“CustOrders”))

Return oChildView

End Function

Thanks & Regards,

Arun Manglick || Tech Lead

Wednesday, September 5, 2007

DataBinding using Eval

DataBinding:

Note:

You can assign any object that implements the IEnumerable, IListSource or IDataSource interface to the DataSource property of a GridView control.

A DataBinding expression is a special type of expression that is not evaluated until runtime. You mark a databinding expression in a page by wrapping the expression in opening <%# and closing %> brackets.

A DataBinding expression isn't evaluated until a control's DataBinding event is raised. When you bind a DataBound control to a DataSource control declaratively, this event is raised automatically. When you bind a DataSource control to a data source programmatically, the DataBinding event is raised when you call the DataBind() method.

Below is the binding syntax:

<%# Eval("Title") %>

<%# Eval("Director") %>

 
The Eval() method is a protected method of the Page class. Behind the scenes, the Page.Eval() method calls the shared (static) DataBinder.Eval() method. 
If you want to be verbose, instead of using the Eval() method, you could use the following two expressions:
 

<%# DataBinder.Eval(Container.DataItem, "Title") %>

<%# DataBinder.Eval(Container.DataItem, "Director") %>

Note

Technically, the Eval() method uses reflection when evaluating the data item to find a property with a certain name. You do pay a performance penalty when you use reflection.As an alternative, you can improve the performance of your DataBinding expressions by casting the data items to a particular type like this:

<%# CType(Container.DataItem, System.Data.DataRowView)("Title")%>

Thanks & Regards,

Arun Manglick || Tech Lead

Monday, September 3, 2007

DataKeys : AutoGenerateSelectButtion, CommandField with CommandName = 'Select'

DataKeys : AutoGenerateSelectButtion, CommandField with CommandName = ‘Select’ & GridView1_SelectedIndexChanged

e.g.: 11.3

GridView1_SelectedIndexChanged -

You can determine which row is selected in a GridView control by using any of the following properties:

SelectedDataKey

Returns the DataKey object associated with the selected row (useful when there are multiple data keys).

SelectedIndex

Returns the (zero-based) index of the selected row.

SelectedValue

Returns the data key associated with the selected row.

SelectedRow

Returns the actual row (GridViewRow object) associated with the selected row.

Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

Response.Write("<b>SelectedDataKey.Value: </b>" & Server.HtmlEncode(GridView1.SelectedDataKey.Value) & "<br />")


Response.Write("<b>DataKey Field 1: </b>" & Server.HtmlEncode(GridView1.SelectedDataKey.Values("au_id")) & "<br />")


Response.Write("<b>DataKey Field 2: </b>" & Server.HtmlEncode(GridView1.SelectedDataKey.Values("title_id")) & "<br />")

End Sub

In General:

A GridView stores data keys (DataKey objects in a collection called the DataKeys collection. This collection is exposed by the GridView control's DataKeys property.

Syntax:

· For Single-Column Datakeys:

DataKey objDataKey = Gridview1.DataKeys[<Row Number>]
Return objDataKey.Value

· For Multi-Column Datakeys:

DataKey objDataKey = Gridview1.DataKeys[<Row Number>]
Return objDataKey.Values[“<Column Name>”]

In most cases, you use the SelectedValue property to determine the value associated with a particular row. The SelectedValue property returns the data key associated with a row. See Below.

Example 1:

    <asp:GridView
        id="grdMovieCategories"
        DataKeyNames="Id"
        DataSourceID="srcMovieCategories"
        AutoGenerateSelectButton="true"
        SelectedRowStyle-CssClass="selectedRow"
        CssClass="gridView"
        Runat="server" />
 
     <asp:SqlDataSource
        id="srcMovieCategories"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        SelectCommand="SELECT Id, Name FROM MovieCategories"
        Runat="server" />
   
     <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        CssClass="gridView"
        Runat="server" />
 
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        SelectCommand="SELECT Title,Director FROM Movies
            WHERE CategoryId=@CategoryId"
        Runat="server">
        <SelectParameters>
        <asp:ControlParameter
            Name="CategoryId"
            ControlID="grdMovieCategories"
            PropertyName="SelectedValue" />
        </SelectParameters>
    </asp:SqlDataSource>
 
 

Example 2:

 

    <asp:GridView
        id="grdMovieCategories"
        DataKeyNames=" FistName, LastName "
        DataSourceID="srcMovieCategories"
        AutoGenerateSelectButton="true"
        SelectedRowStyle-CssClass="selectedRow"
        CssClass="gridView"
        Runat="server" />
 
     <asp:SqlDataSource
        id="srcMovieCategories"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        SelectCommand="SELECT FistName, LastName FROM Employees"
        Runat="server" />
   
     <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        CssClass="gridView"
        Runat="server" />
 
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        SelectCommand="SELECT * FROM Employees
            WHERE FirstName=@FirstName AND LastName=@LastName "
        Runat="server">
        <SelectParameters>
        <asp:ControlParameter
            Name="FirstName"
            ControlID="grdMovieCategories"
            PropertyName='SelectedDataKey("FirstName")’ />
               <asp:ControlParameter
            Name="LastName"
            ControlID="grdMovieCategories"
            PropertyName='SelectedDataKey("LastName")’ />
        </SelectParameters>
    </asp:SqlDataSource>
 

Thanks & Regards,

Arun Manglick || Tech Lead

Thursday, July 5, 2007

Parameters

 

    Protected Sub btnAddEnTry_Click(ByVal sender As Object, ByVal e As EventArgs)

        srcGuestBook.InsertParameters("Name").DefaultValue = txtName.Text

        srcGuestBook.InsertParameters("Comments").DefaultValue = txtComments.Text

        srcGuestBook.Insert()

    End Sub

 

 Protected Sub srcGuestBook_Inserting(ByVal sender As Object, ByVal e As

 SqlDataSourceCommandEventArgs)

        e.Command.Parameters.Add(New SqlParameter("@Name", User.Identity.Name))

    End Sub

 

 

 

 Protected  Sub srcGuestbook_Inserting(ByVal sender As Object, ByVal e As

 ObjectDataSourceMethodEventArgs)

        e.InputParameters.Add("IPAddress", Request.UserHostAddress)

    End Sub

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Wednesday, July 4, 2007

FW: How to Register User Controls and Custom Controls in Web.config

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

From: Arun Manglick [mailto:arun_manglick@persistent.co.in]
Sent: Wednesday, July 04, 2007 6:29 PM
To: 'arunmanglick.post@blogger.com'
Subject: How to Register User Controls and Custom Controls in Web.config

 

Problem:

In previous versions of ASP.NET , to use the custom server controls and user controls on a page, <%@ Register %> directive is used at the top of pages like so:

<%@ Register TagPrefix="ucl" TagName="header" Src="Controls/Header.ascx" %>
<%@ Register TagPrefix="ucl" TagName="footer" Src="Controls/Footer.ascx" %>
<%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %>

Once registered these controls can be used anywhere on the page by using the tagprefix and tagnames configured.


<html>
<body>
    <form id="form1" runat="server">
        <ucl:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

This works fine, but can be a pain to manage when you want to have controls used across lots of pages within your site (especially if you ever move your .ascx files and need to update all of the registration declarations.

Solution:

ASP.NET 2.0 makes control declarations much cleaner and easier to manage. Instead of duplicating them on all your pages, just declare them once within the new pages->controls section with the web.config file of your application:

<?xml version="1.0"?>

<configuration>

  <system.web>
    
    <pages>
      <controls>
        <add tagPrefix="ucl" src="~/Controls/Header.ascx" tagName="header"/>
        <add tagPrefix="ucl" src="~/Controls/Footer.ascx" tagName="footer"/>
        <add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
      </controls>
    </pages>

  </system.web>

</configuration>

Once registered the controls within the web.config file, can then be used similar to above.

<html>
<body>
    <form id="form1" runat="server">
        <ucl:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

Hope this helps,

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Sorting Image in GridView

Hi,

 

protected void gridViewPastOrders_OnSort(object sender, GridViewSortEventArgs e)

    {

        m_SortExp = e.SortExpression;

        m_SortDirection = e.SortDirection;

    }

 

protected void gridViewPastOrders_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        try

        {

            if (e.Row.RowType == DataControlRowType.Header)

            {

                if (String.Empty != m_SortExp)

                {

                    int column =GetSortColumnIndex(this.gridViewPastOrders, m_SortExp);

                    if (column != -1)

                        AddSortImage(e.Row, column, m_SortDirection);

                }

            }

        }

        catch (Exception ex)

        {

            HandleException(ex);

        }

    }

 

--------------------------------------------------------------------------------------------

public int GetSortColumnIndex(GridView gridView, String sortExpression)

        {

            if (gridView == null)

                return -1;

 

            foreach (DataControlField field in gridView.Columns)

            {

                if (field.SortExpression == sortExpression)

                {

                    return gridView.Columns.IndexOf(field);

                }

            }

 

            return -1;

        }

 

        public static void AddSortImage(GridViewRow headerRow, int column, SortDirection sortDirection)

        {

            if (-1 == column)

            {

                return;

            }

            Image sortImage = new Image();

            if (SortDirection.Ascending == sortDirection)

            {

                sortImage.ImageUrl = “”;

            }

            else

            {

                sortImage.ImageUrl = “”;

            }

 

            // Add the image to the appropriate header cell.

            headerRow.Cells[column].Controls.Add(sortImage);

        }

--------------------------------------------------------------------------------------------

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.