Category Archives: DataPager

[RESOLVED] how to create a table and populate it with data without using data controls.

I want to know how we can create a table (or a layout consisting of div's) and poulate it with data from the database. We do this generally using data controls like gridview, datalist etc. But i am restricted by these controls like there is no inbuilt paging with datalist and there is no repeat column in gridview. I just want complete control over the layout as well as the data that goes into it.

I dont know how to do this. Is there anyway of doing it without using the data controls.

 

You have to get data from DB into a dataReader or DataTable and build a dynamic HTML Table from it by adding HTMLTableRow and HTMLTableCells based on the columns that you are getting from DB.

If i get a list of products (List of product class objects (IList<Products>)) then how can i display them in a table.

Also how can i perform paging, sorting, editing and deltion of this data.

invincible_777

If i get a list of products (List of product class objects (IList<Products>)) then how can i display them in a table.

Also how can i perform paging, sorting, editing and deltion of this data.

That would be a bunch of work on the code side if you dont use Databound controls....

I would say go for a simple Repeater control...where you have more flexibility of configuring on the code side...

PS - I dont say it is possible with complete code configuration for List, rather i would say it is difficult and would make life more complex and more bug prone...

Thanks.

Actually I run into a number of problems [read restrictions ;)] when I use any of the databound control. Is there any databound control which can be partly treated as universal. I just dont want the .net engine to generate to much code for me.

I thought I would learn the method of dynamically generating tables (or any other type of content for that matter) and use it in any situation. I know databound controls are here to help us from that mess but i find them more confusing than helpful.

In MVC there are no controls; then how do those guys manage to get the stuff working.

Normally I use gridview to display dynamic data. This control supports paging, sorting, editing, and deleting. Also, I can present dynamic nested gridviews to present parent and child data in one grid look. I have used with various data sources, such list<object> like you and common data table or dataset without the problem. what do you mean that problem with reading restriction please?

@jubbabo: If I want to display gridview in column format (similar to RepeatColumns funtionality of datalist) then I am unable to do so..

Similarly I dont have inbuilt paging in datalist..

Now if I have to combine the above two functionalities I am unable to do so,,

So i limit the usage of the controls and have a complete different approach to develope applications..

I got it. GridView can repeat data as row only, whereas data list can repeat data as row or column direction.

Probably you can use both controls into one, such as gridview as master and each row has data list nested, or vice versa.

Can you give me the sample of table output to see the implementing possibility?

<table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                <asp:ListView ID="lstProductList" GroupItemCount="3" runat="server" OnItemDataBound="lstProductList_ItemDataBound">
                                                                                    <LayoutTemplate>
                                                                                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                            <asp:PlaceHolder ID="groupPlaceholder" runat="server" />
                                                                                        </table>
                                                                                    </LayoutTemplate>
                                                                                    <GroupTemplate>
                                                                                        <tr>
                                                                                            <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                                                                                        </tr>
                                                                                    </GroupTemplate>
                                                                                    <ItemTemplate>
                                                                                        <td width="265" align="left" valign="top" class="detail_border curvecorners1">
                                                                                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                                <tr>
                                                                                                    <td align="left" valign="top">
                                                                                                        &nbsp;
                                                                                                    </td>
                                                                                                </tr>
                                                                                                <tr>
                                                                                                    <td align="left" valign="top" class="pop_border">
                                                                                                        <table width="96%" border="0" align="center" cellpadding="0" cellspacing="0">
                                                                                                            <tr>
                                                                                                                <td width="30%" align="left" valign="top">
                                                                                                                    <asp:HiddenField ID="hfID" runat="server" Value='<%# Eval("Product_ID") %>' />
                                                                                                                    <asp:Image ID="imgPicture" runat="server" Width="67" Height="117" />
                                                                                                                </td>
                                                                                                                <td width="70%" align="left" valign="top">
                                                                                                                    <table width="100%" border="0" align="left" cellpadding="0" cellspacing="0">
                                                                                                                        <tr>
                                                                                                                            <td align="left" valign="top">
                                                                                                                                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                                                                    <tr>
                                                                                                                                        <td height="30" align="left" valign="top" class="mobile_title">
                                                                                                                                            <strong>
                                                                                                                                                <asp:Literal ID="hlTitle" runat="server" Text='<%# Eval("Product_Name") %>'></asp:Literal></strong></strong>
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                    <tr>
                                                                                                                                        <td align="left" valign="top">
                                                                                                                                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                                                                                <tr>
                                                                                                                                                    <td width="84%" align="left" valign="top">
                                                                                                                                                        <asp:Literal ID="hlShortDesc" runat="server" Text='<%# Eval("Product_ShortDescription") %>'></asp:Literal>
                                                                                                                                                    </td>
                                                                                                                                                </tr>
                                                                                                                                                <tr>
                                                                                                                                                    <td align="left" valign="top">
                                                                                                                                                        &nbsp;
                                                                                                                                                    </td>
                                                                                                                                                </tr>
                                                                                                                                            </table>
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                    <tr>
                                                                                                                                        <td align="left" valign="top">
                                                                                                                                           
                                                                                                                                            <asp:Image ID="imgStar" runat="server" ImageUrl="~/images/star_img.gif" Width="67" Height="16" AlternateText="star" />
                                                                                                                                            
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                    <tr>
                                                                                                                                        <td align="left" valign="top" class="mobile_prize">
                                                                                                                                            <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                    <tr>
                                                                                                                                        <td align="left" valign="top">
                                                                                                                                            &nbsp;
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                </table>
                                                                                                                            </td>
                                                                                                                        </tr>
                                                                                                                        <tr>
                                                                                                                            <td align="left" valign="top">
                                                                                                                                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                                                                    <tr>
                                                                                                                                        <td align="left" valign="middle" class="buy_now" style="font-size: 11px;">
                                                                                                                                            <a href="#">Add Reviews</a>
                                                                                                                                        </td>
                                                                                                                                        <td width="5" align="left" valign="top">
                                                                                                                                            &nbsp;
                                                                                                                                        </td>
                                                                                                                                        <td align="left" valign="middle" class="add_fav_btn">
                                                                                                                                            <a href="#">Add To Favorite</a>
                                                                                                                                        </td>
                                                                                                                                    </tr>
                                                                                                                                </table>
                                                                                                                            </td>
                                                                                                                        </tr>
                                                                                                                        <tr>
                                                                                                                            <td align="left" valign="top">
                                                                                                                                &nbsp;
                                                                                                                            </td>
                                                                                                                        </tr>
                                                                                                                    </table>
                                                                                                                </td>
                                                                                                            </tr>
                                                                                                        </table>
                                                                                                    </td>
                                                                                                </tr>
                                                                                                <tr>
                                                                                                    <td align="left" valign="top">
                                                                                                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                                                                            <tr height="30px">
                                                                                                               
                                                                                                                <td width="100%" align="center" valign="middle">
                                                                                                                    <asp:CheckBox Text="COMPARE" CssClass="pro_compare" ID="chkCompare" runat="server" />
                                                                                                                    <%--onclick="javascript: check(1,1);" --%>
                                                                                                                    <asp:HiddenField ID="hdfProducName" runat="server" Value='<%# Eval("Product_Name") %>' />
                                                                                                                    <asp:HiddenField ID="hdfProductId" runat="server" Value='<%# Eval("Product_ID") %>' />
                                                                                                                </td>
                                                                                                               
                                                                                                            </tr>
                                                                                                        </table>
                                                                                                    </td>
                                                                                                </tr>
                                                                                            </table>
                                                                                        </td>
                                                                                    </ItemTemplate>
                                                                                    <ItemSeparatorTemplate>
                                                                                        <td style="width: 15px">
                                                                                        </td>
                                                                                    </ItemSeparatorTemplate>
                                                                                    <GroupSeparatorTemplate>
                                                                                        <tr style="height: 15px">
                                                                                        </tr>
                                                                                    </GroupSeparatorTemplate>
                                                                                </asp:ListView>
                                                                            </table>

 

<div class="page_line_Left_cont2">
                                                                                <asp:DataPager ID="pg" runat="server" PagedControlID="lstProductList" PageSize="3"
                                                                                    OnPreRender="pg_PreRender">
                                                                                    <Fields>
                                                                                        <%--<asp:NextPreviousPagerField ButtonType="Image" ShowFirstPageButton="False" ShowNextPageButton="False"
                                                                                            ShowPreviousPageButton="True" PreviousPageImageUrl="~/images/previous.gif" PreviousPageText="Prev"/>--%>
                                                                                        <asp:NumericPagerField 
                                                                                             ButtonCount="6" ButtonType="Link" NumericButtonCssClass="numberink" CurrentPageLabelCssClass="numberink2"
                                                                                            RenderNonBreakingSpacesBetweenControls="true" NextPreviousButtonCssClass="nextprev"/>
                                                                                        <%--<asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="false" ShowNextPageButton="True"
                                                                                            ShowPreviousPageButton="False" ButtonCssClass="previous"/>--%>
                                                                                    </Fields>
                                                                                </asp:DataPager>
                                                                            </div>

 

 private void BindProducts()
    {
        IList<Product> objProdList = CProduct.Instance().fn_getProductBySubCatID(iSubCatID);
        lstProductList.DataSource = objProdList;
        lstProductList.DataBind();
    }

 

protected void lstProductList_ItemDataBound(object sender, ListViewItemEventArgs e)
    {

        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            Image imgPicture = (Image)e.Item.FindControl("imgPicture");
            Literal Literal1 = (Literal)e.Item.FindControl("Literal1");
            HiddenField hfID = (HiddenField)e.Item.FindControl("hfID");
            int id = int.Parse(hfID.Value);
            IList<ProductImage> objProdImg = CProductImage.Instance().fn_getProductImageByProductID(id);
            if (objProdImg.Count() > 0)
            {
                imgPicture.ImageUrl = "~/admin/Upload/Product/Image/" + objProdImg[0].ProductImage_Image;
            }
            else
            {
                imgPicture.ImageUrl = "~/admin/images/noimage.gif";
            }
            IList<ProductPrice> objProdPrice = CProductPrice.Instance().fn_getProductPriceByProductID(id);
            if (objProdPrice.Count > 0)
            {
                Literal1.Text = objProdPrice[0].ProductPrice_Price.ToString();
            }
            else
            {
                Literal1.Text = "---";
            }


        }
    }
    protected void pg_PreRender(object sender, EventArgs e)
    {

        if (chk_BrandName.SelectedIndex != -1 && chk_Type1.SelectedIndex != -1)
        {
            alSelectedProductBrandIds = (ArrayList)Session["alSelectedProductBrandIds"];
            alSelectedProductsProductIDs = (ArrayList)Session["alSelectedProductsProductIDs"];
            IList<Product> objProdList = CProduct.Instance().fn_getProductsByBrandIDsandProductIDs(alSelectedProductBrandIds, alSelectedProductsProductIDs);
            //IList<Product> objProdList = CProduct.Instance().fn_getProductsBySubCategoryIdandBrandIDs(alSelectedProductBrandIds);
            lstProductList.DataSource = objProdList;
            lstProductList.DataBind();               
        }
        else if (chk_BrandName.SelectedIndex != -1)
        {
            alSelectedProductBrandIds = (ArrayList)Session["alSelectedProductBrandIds"];
            IList<Product> objProdList = CProduct.Instance().fn_getProductsBySubCategoryIdandBrandIDs(alSelectedProductBrandIds);
            //IList<Product> objProdList = CProduct.Instance().fn_getProductsBySubCategoryIdandBrandIDs(alSelectedProductBrandIds);
            lstProductList.DataSource = objProdList;
            lstProductList.DataBind();
        }
        else if (chk_Type1.SelectedIndex != -1 || chk_Type2.SelectedIndex != -1 || chk_Type3.SelectedIndex != -1)
        {           
            alSelectedProductsProductIDs = (ArrayList)Session["alSelectedProductsProductIDs"];
            IList<Product> objProdList = CProduct.Instance().fn_getProductsByProductIDs(alSelectedProductsProductIDs);
            //IList<Product> objProdList = CProduct.Instance().fn_getProductsBySubCategoryIdandBrandIDs(alSelectedProductBrandIds);
            lstProductList.DataSource = objProdList;
            lstProductList.DataBind();
        }
        else
        {
            IList<Product> objProdList = CProduct.Instance().fn_getProductBySubCatID(iSubCatID);
            lstProductList.DataSource = objProdList;
            lstProductList.DataBind();
        }


    }

Hi invincible_777,

I think you can use the reapter with the paging, it can meet your demand.

If you use the table, it is complex and easy to be error.

Please check the following link:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=345

http://www.codeproject.com/KB/webforms/Aspnet_Repeater_Control.aspx

http://forums.asp.net/t/1371448.aspx

[RESOLVED] have to click twice on pager to see items in listview

Hi

 

I have list view and datapager, it worked fine, but when i click second page, i have to clicked twice, first click did not go to second page, had to click twice to see items.

 

please any idea.

You might be setting something on first click that is triggering the second click to work. Post your code so we could help you better.

put the binding of your listview on the prerender event something like this

protected void Datapager_PreRender(object sender, EventArgs e)
 {
       //Bind your listview here
 }

 

hope this helps you

thanks for reply,

 

i have sorted it out, i put OnpagePropertiesChanged in list view and below method..

let say, i got 10 pages and 12345 etc for pages, i clicked on 2 and did not go to the page, i have to click twice to see items on second page. the below code worked

protected void sourceListView_OnPagePropertiesChanged(object sender, EventArgs e)
        {
            sourceListView.DataBind();
        }

[RESOLVED] What is the trick in versions older than IE8 to get the width's for listviews to work correctly when they are set to auto.

With IE 8 and beyond, everything works fines.  But with IE 7 and older, if I don't specify the widths for listviews everything goes wild.  What is the trick to fixing the problem?

Hi,

JAYHAWKER

But with IE 7 and older, if I don't specify the widths for listviews everything goes wild.  What is the trick to fixing the problem?

According to your description ,I can hardly reproduce the issue at my side,could you please provide more information about your code?If so ,we can find the issue more conveniently and provide further suggestions for you.

 

<div>Thanks for the reply.</div> <div></div> <div>I guess I spoke wrong, actually the listview itself does expand automatically, but if I wrap the listview in a panel, and place another header panel above the listview in the wrapping panel with the following code, the header panel width doesn't set correctly when setting width to 100% or automatic in browser versions older then 8.</div> <div>
<div><asp:Panel runat="server" id="pnlListView1" class="list"
                style="top: 200px; left: 200px; position: absolute" visible="false">
            <asp:Panel ID="pnlListView1Header" runat="server" class="title" style="width: 100%">
                <asp:Label ID="label1" runat="server" Text="This is a Test" class="h1" EnableTheming="false"> </asp:Label>
             </asp:Panel>
                <asp:ListView ID="ListView1" runat="server"
                    DataKeyNames="ContactID"
                    DataSourceID="SqlDataSourceListView1"
                    OnItemDataBound="ListView1_ItemDataBound">
                                                                          
                <ItemTemplate>
                    <tr class="even">
                         <td id="Td3" style="display: none" runat="server">
                              <asp:Label ID="Label2" runat="server" Text='<%# Eval("ContactID") %>'  />
                        </td>
                        <td style="white-space: nowrap; text-align: left" class="label" >   &nbsp;
                                <asp:Label ID="Label3" runat="server" style="white-space: nowrap"  Text='<%# Eval("FullName") %>' />
                        </td></div><div><div>                 </tr></div><div>             </ItemTemplate>
                    
               <AlternatingItemTemplate>
                  <tr class="odd">
                         <td id="Td3" style="display: none" runat="server">
                              <asp:Label ID="Label2" runat="server" Text='<%# Eval("ContactID") %>'  />  
                        </td>
                        <td style="white-space: nowrap; text-align: left" class="label" >   &nbsp;
                                <asp:Label ID="Label3" runat="server" style="white-space: nowrap"  Text='<%# Eval("FullName") %>' />                                 
                        </td></div><div>                    </tr></div><div>                </AlternatingItemTemplate></div><div> </div><div>

<LayoutTemplate>

</td> </tr> <table ID="Table2" runat="server" cellpadding="0" cellspacing="0"> <tr ID="Tr1" runat="server" style="padding-left: 0px"> <td ID="Td1" runat="server" style="padding-left: 0px"> <table ID="itemPlaceholderContainer" runat="server" cellpadding="0" cellspacing="0" class="datatable"> <tr ID="Tr2" runat="server"> <th ID="Th1" runat="server" style="width: 50px; white-space: nowrap"> &nbsp; </th> <th ID="Th2" runat="server" style="display: none"> </th> <th ID="Th3" runat="server"> <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument="FullName" CommandName="Sort">Name</asp:LinkButton> </th> </tr> <tr ID="itemPlaceholder" runat="server"> <%--Important--%> </tr> </table> </td> </tr> </table> <tr id="Tr3" runat="server" style="text-align: center; background-image:url(~/images/ListView/gray_hd_bg.png);"> <td id="Td2" runat="server" style="text-align: center;" align="center"> <div align="center"> <asp:DataPager ID="DataPager1" runat="server"> <Fields> <asp:NextPreviousPagerField FirstPageText="First Page |" ShowFirstPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False"/> <asp:NextPreviousPagerField PreviousPageText=" Previous " ShowFirstPageButton="False" ShowNextPageButton="False" /> <asp:NumericPagerField /> <asp:NextPreviousPagerField NextPageText=" Next |" ShowFirstPageButton="False" ShowPreviousPageButton="False" /> <asp:NextPreviousPagerField LastPageText=" Last Page" ShowLastPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" /> </Fields> </asp:DataPager> </div> </td> </tr> </table> </LayoutTemplate> </asp:ListView>

</asp:Panel>

</div> <div> </div> </div> </div> <div> </div> <div> CSS:</div> <div> </div> <div>

.list{

z-index: 1020;

font-size:11px;

font-family:Tahoma;

border:solid 1px #191970;

background-color:#fff;

padding:1px;

width: auto;

margin-right: 100%;

margin-bottom: 5px;

border-radius: 10px 10px 10px 10px;

white-space: nowrap; min-width: 500px;

overflow: visible;}

/* the .list .title is in the header of the listview*/

 

.list .title{

background-color: #323a4B;

color:#fff; height:30px;

text-align:center;

line-height:30px;

font-size:16px;

font-weight:bold;

width: 100%;

min-width: 100%;

border-radius: 8px 8px 0px 0px;

margin-right: 0px;

white-space:nowrap;

overflow: visible;

}

</div> <div> </div> <div> Any ideas?</div> <div> </div>

[RESOLVED] Error : Specified argument was out of the range of valid values.

 hi , i m trying to implement DataPager in my ListView here i m facing one problem

 not able to find the ListView COntrol its shows me error as

  System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. on

 DropDownList ddl = (DropDownList)ProductListPager.Controls[0].FindControl("PageJump");

 here is my code plz let m e know where i m wrong.

 

protected void Page_Load(object sender, EventArgs e)
    {
        //ProductListPagerSimple.SetPageProperties(10, 10, true);
        int currentPage = (ProductListPager.StartRowIndex / ProductListPager.PageSize) + 1;
        int totalPages = ProductListPager.TotalRowCount / ProductListPager.PageSize;
        PageMessage.Text = string.Format("You are viewing page {0} of {1}", currentPage, totalPages);

        //Populate the DropDownList if needed
        DropDownList ddl = (DropDownList)ProductListPager.Controls[0].FindControl("PageJump");
        if (ddl.Items.Count == 0)
        {
            //Add a list item for each page
            for (int i = 1; i <= totalPages; i++)
            {
                ddl.Items.Add(i.ToString());
            }

            //Set the DDL to the appropriate page value
            ddl.Items.FindByValue(currentPage.ToString()).Selected = true;
        }

    }

    protected void PageJump_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList PageJumpDDL = (DropDownList)sender;
        int pageNo = Convert.ToInt32(PageJumpDDL.SelectedValue);

        int startRowIndex = (pageNo - 1) * ProductListPager.PageSize;

        ProductListPager.SetPageProperties(startRowIndex, ProductListPager.PageSize, true);
    }

 

and on html

 

 <asp:ListView ID="ProductList" runat="server" DataSourceID="ProductDataSource">
        <LayoutTemplate>
            <h3>Product Listing</h3>
            <blockquote>
                <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>                        
            </blockquote>
        </LayoutTemplate>
        
        <ItemSeparatorTemplate>
            <hr />
        </ItemSeparatorTemplate>

        <ItemTemplate>
            <h4><%#Eval("ProductName")%> (<%# Eval("CategoryName") %>)</h4>
            Available at <%#Eval("UnitPrice", "{0:c}")%>, 
            with <%#Eval("QuantityPerUnit")%>.
        </ItemTemplate>
    </asp:ListView>
<asp:DataPager ID="ProductListPager" runat="server" PagedControlID="ProductList" 
        PageSize="5">
        <Fields>
            <asp:TemplatePagerField>
                <PagerTemplate>
                    Jump to a specific page:
                    <asp:DropDownList runat="server" ID="PageJump" AutoPostBack="true" 
                        onselectedindexchanged="PageJump_SelectedIndexChanged">
                    </asp:DropDownList>
                </PagerTemplate>
            </asp:TemplatePagerField>
        </Fields>
    </asp:DataPager>
    <div class="StatusMessage">
        <asp:Label ID="PageMessage" runat="server"></asp:Label>
    </div>

plz help me,

basaiclly i m trying to add the two section for paging 1. selecting drop dwon number and 2. clicking on next prev like that

 

 

Do you have any items in DataPager? Use breakpoint, it's easy to find out the controls that way,

this error is comes because ProductListPager.Controls have 0 item and you are trying to access its frist item hence that is giving you an error.

You have to do debug your code and find out how can you achive your componets....... first you have to understand ProductListPager controls interanal structure then you can access any of its child controls.

just refer this article http://www.4guysfromrolla.com/articles/021308-1.aspx and let me klnow where i m wrong

i m using same code

 

Try to use DataPager.FindControl(....)

Thanks.

thats right here i want to ask one question realted with vb.net .

here is the code they use to maintain the current page and total page count

 

Partial Class DataPagerDemos_TemplatedPaging
    Inherits BasePage

    Protected Sub ProductList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ProductList.DataBound
        Dim currentPage As Integer = (ProductListPager.StartRowIndex / ProductListPager.PageSize) + 1
        Dim totalPages As Integer = ProductListPager.TotalRowCount / ProductListPager.PageSize
        PageMessage.Text = String.Format("You are viewing page {0} of {1}", currentPage, totalPages)

        'Populate the DropDownList if needed
        Dim ddl As DropDownList = CType(ProductListPager.Controls(0).FindControl("PageJump"), DropDownList)
        If ddl.Items.Count = 0 Then
            'Add a list item for each page
            For i As Integer = 1 To totalPages
                ddl.Items.Add(i.ToString())
            Next

            'Set the DDL to the appropriate page value
            ddl.Items.FindByValue(currentPage.ToString()).Selected = True
        End If
    End Sub

    Protected Sub PageJump_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim PageJumpDDL As DropDownList = CType(sender, DropDownList)
        Dim pageNo As Integer = Convert.ToInt32(PageJumpDDL.SelectedValue)

        Dim startRowIndex As Integer = (pageNo - 1) * ProductListPager.PageSize

        ProductListPager.SetPageProperties(startRowIndex, ProductListPager.PageSize, True)
    End Sub
End Class

here wht i have done is simply convert that into the c# and at t time of page load im getting this error becuase they have mentaion that in

ProductList_DataBound() event and my code is in page_load so plz let me know how i can pass that and at a time of page_load

 

if i use DataPager.FindControl(....)

then it will give me error on this line.

 

Object reference not set to an instance of an object.

 if (ddl.Items.Count == 0)
Line 39: {

Hi,

kirank28

not able to find the ListView COntrol its shows me error as

  System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. on

 DropDownList ddl = (DropDownList)ProductListPager.Controls[0].FindControl("PageJump");

First of all ,I would recommend that please modify your code like this to get the value of totalPages variable:

int totalPages = (int)Math.Ceiling((double)ProductListPager.TotalRowCount / (double)ProductListPager.PageSize);

The Math.Ceiling Method returns the smallest integer greater than or equal to the specified number.

According to your code and description ,I get that you want to get the dropdownlist control object which is contained in a DataPager control by using FindControl method.

I would like to suggest you to use the code as below to get the dropdownlist control object which as you mentioned in your post.

//Populate the DropDownList if needed
        foreach (Control FileItem in this.ProductListPager.Controls)
        {
            foreach (Control ctrl in FileItem.Controls)
            {
                if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                {
                    DropDownList ddl = (DropDownList)ctrl;
                    if (ddl.Items.Count == 0)
                    {
                        //Add a list item for each page
                        for (int i = 1; i <= totalPages; i++)
                        {
                            ddl.Items.Add(i.ToString());
                        }

                        //Set the DDL to the appropriate page value
                        ddl.Items.FindByValue(currentPage.ToString()).Selected = true;
                    }
                }
            }
        }

kirank28

 let me klnow where i m wrong

kirank28

and
my code is in page_load so plz let me know how i can pass that and at a time of page_load 

 Please check the complete sample below which describes how to use a DataPager control with a ListView control and also includes how to get /bind data to a dropdownlist control that contained in the DataPager control:

Please create a new page to demo the sample.

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListView ID="ProductList" runat="server">
            <LayoutTemplate>
                <h3>
                    Product Listing</h3>
                <blockquote>
                    <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
                </blockquote>
            </LayoutTemplate>
            <ItemSeparatorTemplate>
                <hr />
            </ItemSeparatorTemplate>
            <ItemTemplate>
                <h4>
                    <%#Eval("ProductName")%>
                    (<%# Eval("CategoryName") %>)</h4>
                Available at
                <%#Eval("UnitPrice", "{0:c}")%>, with
                <%#Eval("QuantityPerUnit")%>.
            </ItemTemplate>
        </asp:ListView>
        <asp:DataPager ID="ProductListPager" runat="server" PagedControlID="ProductList"
            PageSize="2">
            <Fields>
                <asp:TemplatePagerField>
                    <PagerTemplate>
                        Jump to a specific page:
                        <asp:DropDownList runat="server" ID="PageJump" AutoPostBack="true" OnSelectedIndexChanged="PageJump_SelectedIndexChanged">
                        </asp:DropDownList>
                    </PagerTemplate>
                </asp:TemplatePagerField>
            </Fields>
        </asp:DataPager>
        <div class="StatusMessage">
            <asp:Label ID="PageMessage" runat="server"></asp:Label>
        </div>
    </div>
    </form>
</body>
</html>

2.Code in page(.cs):

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    public void Bind()
    {
        // Bind Data to ListView control.
        // You can get the data from your own database.
        // I get the datatable like this in order to run the sample more conveniently.
        this.ProductList.DataSource = getDB();
        this.ProductList.DataBind();


        //ProductListPagerSimple.SetPageProperties(10, 10, true); 
        int currentPage = (ProductListPager.StartRowIndex / ProductListPager.PageSize) + 1;
        int totalPages = (int)Math.Ceiling((double)ProductListPager.TotalRowCount / (double)ProductListPager.PageSize);
        PageMessage.Text = string.Format("You are viewing page {0} of {1}", currentPage, totalPages);

       //Populate the DropDownList if needed
        foreach (Control FileItem in this.ProductListPager.Controls)
        {
            foreach (Control ctrl in FileItem.Controls)
            {
                if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                {
                    DropDownList ddl = (DropDownList)ctrl;
                    if (ddl.Items.Count == 0)
                    {
                        //Add a list item for each page
                        for (int i = 1; i <= totalPages; i++)
                        {
                            ddl.Items.Add(i.ToString());
                        }

                        //Set the DDL to the appropriate page value
                        ddl.Items.FindByValue(currentPage.ToString()).Selected = true;
                    }
                }
            }
        }
        
    }
    // You can get the data from your own database.
    // I get the datatable like this in order to run the sample more conveniently.
    private DataTable getDB()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductName");
        dt.Columns.Add("CategoryName");
        dt.Columns.Add("UnitPrice");
        dt.Columns.Add("QuantityPerUnit");
        dt.Rows.Add(new object[] { "ProductName_1", "CategoryName_1", "1001", "1" });
        dt.Rows.Add(new object[] { "ProductName_2", "CategoryName_2", "1002", "2" });
        dt.Rows.Add(new object[] { "ProductName_3", "CategoryName_3", "1003", "3" });
        dt.Rows.Add(new object[] { "ProductName_4", "CategoryName_4", "1004", "4" });
        dt.Rows.Add(new object[] { "ProductName_5", "CategoryName_5", "1005", "5" });
        dt.Rows.Add(new object[] { "ProductName_11", "CategoryName_11", "10011", "11" });
        dt.Rows.Add(new object[] { "ProductName_21", "CategoryName_21", "10021", "21" });
        dt.Rows.Add(new object[] { "ProductName_31", "CategoryName_31", "10031", "31" });
        dt.Rows.Add(new object[] { "ProductName_41", "CategoryName_41", "10041", "41" });
        dt.Rows.Add(new object[] { "ProductName_51", "CategoryName_51", "10051", "51" });
        dt.Rows.Add(new object[] { "ProductName_111", "CategoryName_111", "100111", "111" });
        dt.Rows.Add(new object[] { "ProductName_211", "CategoryName_211", "100211", "211" });
        dt.Rows.Add(new object[] { "ProductName_311", "CategoryName_311", "100311", "311" });
        dt.Rows.Add(new object[] { "ProductName_411", "CategoryName_411", "100411", "411" });
        dt.Rows.Add(new object[] { "ProductName_511", "CategoryName_511", "100511", "511" });
        return dt;
    }

    protected void PageJump_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList PageJumpDDL = (DropDownList)sender;
        int pageNo = Convert.ToInt32(PageJumpDDL.SelectedValue);

        int startRowIndex = (pageNo - 1) * ProductListPager.PageSize;

        ProductListPager.SetPageProperties(startRowIndex, ProductListPager.PageSize, true);

        // ReBind.
        Bind();
    }

Hope it can help you.

[RESOLVED] Get the CommandArgument in the Page_Load

Hi All,

Here is my problem:

I have created a custom user control allowing to display a ListView of LinkButtons.

Code inline:

 <asp:ListView ID="ListView" runat="server">
                <LayoutTemplate>
                    <ul id="Ul1" runat="server">
                        <li id="ItemPlaceholder" runat="server"></li>
                    </ul>
                    <asp:DataPager runat="server" ID="DataPager" PageSize="30">
                        <Fields>
                            <asp:NumericPagerField ButtonCount="10"
                                PreviousPageText="<-"
                                NextPageText="->" />
                        </Fields>
                    </asp:DataPager>
                </LayoutTemplate>
            <ItemTemplate>
                <li id="Li1" style="float:left; display:inline; width:50%;" runat="server">
                        <asp:LinkButton ID="LinkButton" runat="server" ToolTip='<%# Eval("Form.Name") %>' OnCommand="LinkButton_Command" CommandArgument='<%# Eval("Id") %>' Text='<%# Eval("Form.Name").ToString().Length >= 17 ? Eval("Form.Name").ToString().Substring(0,16)+"..." : Eval("Form.Name").ToString() %>'/>
                    </li>
                    <li id="Li2" style="float:left; display:inline; width:50%;" runat="server">
                        <asp:Label ID="FormSubmissionDate" runat="server" Text='<%# Eval("SubmissionDate", "{0: MMMM d, yyyy}")%>'></asp:Label>
                    </li>
            </ItemTemplate>
        </asp:ListView>

Code behind:

        protected void LinkButton_Command(object sender, CommandEventArgs args)
        {

    this.IdToEdit = Convert.ToInt32(args.CommandArgument, CultureInfo.InvariantCulture);

         }

What I would like to do is to get the value of this.IdToEdit in the Page_Load method of the page containing the UserControl.
How can I do that?

Thanks for your help,

Check this post - http://geekswithblogs.net/rashid/archive/2007/09/13/Asp.net-List---Data-Editing.aspx - on how to find controls on ListView.

Thanks shared.kazi for your reply.

My problem is not to find controls on ListView but to get the CommandEventArgs argument which is in the code behind of my UserControl, in the code behind of the page containing the UC...

Also, the LinkButtons are generated dynamically. And, I would like to get the ID passed in the CommandArgument of the LinkButton which has been clicked.

Asphalt06

this.IdToEdit = Conver...........

If IdToEdit is, or is made, a public property on the UserControl then you'd be able to read it directly off the UserControl instance on the containing page, with yourUserControlInstanceID.IdToEdit.

 

However, in terms of the page lifecycle, the containing page's load event would occur before the OnCommand event of the LinkButton sets that property; you could raise an event from the UserControl and subscribe to it on the containing page (Here's an example that would help), passing the ID.

As Pete says, the Page_Load event fires before the command event. Why do you need the command arguments in Page_Load? What is it that you need to do there that you can't do in the command event procedure?