i have gridview with lots of records, so had to use ObjectDataSource so as to fetch only the records that will be displayed on the page i.e. if there are total 100 records, and page size is 10, on each page click only 10 records are fetched from DB.
Please find the code below
///aspx
<asp:GridView ID="grdModulesList" CssClass="moduleList" runat="server"
AutoGenerateColumns="False" HeaderStyle-Font-Size="Smaller"
Font-Size="Small" AllowPaging="true" AllowSorting="True" OnRowCreated="grdModulesList_RowCreated"
OnRowDataBound="grdModulesList_RowDataBound" BackColor="White" BorderColor="Blue"
BorderStyle="None" BorderWidth="1px" CellPadding="3" PageSize="20">
<Columns>
<asp:BoundField DataField="collection_id" Visible="False" />
<asp:BoundField HeaderText="Item" />
<asp:BoundField HeaderText="Module Name" DataField="module_name" SortExpression="module_name"
ControlStyle-CssClass="moduleName" />
<asp:BoundField HeaderText="File Name" DataField="module_file_name" SortExpression="module_file_name" />
<asp:BoundField HeaderText="ID" DataField="defect_number" SortExpression="defect_number" />
<asp:BoundField HeaderText="Actions" />
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" CssClass="grid_width" BorderWidth="2px"
Height="20px" />
<PagerStyle BackColor="#FFFF99" ForeColor="Red" HorizontalAlign="Center" Height="20px" />
<FooterStyle ForeColor="black" Font-Bold="true" />
<SelectedRowStyle Font-Size="Smaller" />
<HeaderStyle Font-Size="Smaller" BorderStyle="Solid" BackColor="Gold" Font-Bold="True"
ForeColor="Black" Height="30px" />
<AlternatingRowStyle BorderColor="#3366FF" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
//.aspx.cs
ObjectDataSource ods = new ObjectDataSource();
ods.ID = "ods";
ods.SelectMethod = "GRAD_ModuleListforCollection_Subset"; //method to fetch records from DB
ods.EnablePaging = true;
ods.TypeName = "pmAdmin.classes.data.ApplicationData";
ods.StartRowIndexParameterName = "StartRecord";
ods.MaximumRowsParameterName = "PageSize";
ods.SortParameterName = "SortBy";
ods.SelectCountMethod = "GRAD_Total_Modules";
Parameter p1 = new Parameter("userID", TypeCode.String, userId);
ods.SelectParameters.Add(p1);
panelModuleList.Controls.Add(ods); //add objectDatasource control to a panel
grdModulesList.DataSourceID = ods.ID;
grdModulesList.DataBind();
//method GRAD_ModuleListforCollection_Subset
public System.Data.DataSet GRAD_ModuleListforCollection_Subset(string userID, int StartRecord, int PageSize, string SortBy)
{}
records are correctly binded to Gridview, but the issue is the method used to fetch the records from DB i.e.GRAD_ModuleListforCollection_Subset is called twice for each click on page.
example : if i click on page 2 the method is called
() first time with startRecord=0,pagesize=20
() called second time with startRecord=20,pagesize=20
after click on page 2 if i click page 3
() first time with startRecord=20,pagesize=20
() called second time with startRecord=40,pagesize=20
for every page click, first load is having previous value.
Kindly help me in resolving this.
Thanks in advance.
made the following changes to make it work
enable caching for objectDatasource
ods.EnableCaching = true;
set Session["sortorder"]
grdModulesList.DataSourceID = ods.ID;
grdModulesList.DataBind();
if (Session["sortorder"] == null)
Session["sortorder"] = "Ascending";
add gridview sorting event
protected void grdModulesList_Sorting(object sender, GridViewSortEventArgs e)
{
ods.SelectParameters["SortBy"].DefaultValue = GetSortExpr(e.SortExpression);
e.Cancel = true; //We have to do this or we will get an exception
}
public string GetSortExpr(string sortExp)
{
if (Session["sortorder"].ToString() == "Ascending")
{
Session["sortorder"] = "Descending";
return sortExp + " DESC";
}
else
{
Session["sortorder"] = "Ascending";
return sortExp + " ASC";
}
}
if you declare the ObjectDataSource and all its setting in Markup portion (.aspx), then the Select method is called twice only when page is requested for very first time ( PageIndex defaults to 1).
when you select page 2 from paging links, it will call only once the select method then the SelectCount method.
Related
I have an ASP.NET WebForms Application and am encountering one of the oddest problems in my nine months of coding in ASP.NET.
I added two new pages that both use Telerik Radgrids. Both Radgrids are identical, so I will focus on one of them in the hopes that solving one of the problems will solve the other.
Html
<telerik:RadGrid ID="_radgrid" runat="server" Width="100%" Visible="true"
AutoGenerateColumns="false" OnSortCommand="_btnSearch_Click" PagerStyle-AlwaysVisible="true"
Skin="Office2007" AllowFilteringByColumn="true" AllowSorting="true" AllowPaging="true"
PageSize="50" OnNeedDataSource="_radgrid_NeedDataSource" OnItemDataBound="_radgrid_OnItemDataBound"
AllowMultiRowSelection="true">
<MasterTableView AllowFilteringByColumn="true" CommandItemDisplay="TopAndBottom">
<CommandItemTemplate>
<asp:Button ID="_btnResolve" runat="server" Text="Resolve" OnClick="_btnResolve_Click"
Visible="False" ClientIDMode="Inherit" />
</CommandItemTemplate>
<NoRecordsTemplate>
No records to display.</NoRecordsTemplate>
<Columns>
<telerik:GridBoundColumn DataField="Id" Visible="false" />
<telerik:GridBoundColumn DataField="Resolved" Visible="false" />
<telerik:GridClientSelectColumn UniqueName="CheckboxSelectColumn" FooterText="CheckBoxSelect footer"
Visible="false" />
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Id" AllowFiltering="false"
DataNavigateUrlFormatString="~/UpdatePage.aspx?Id={0}"
Text="Update" UniqueName="UpdateHyperLink" />
<telerik:GridBoundColumn DataField="TradingPartnerName" HeaderText="Trading Partner Name" />
<telerik:GridBoundColumn DataField="DocumentType" HeaderText="Transaction Set" />
<telerik:GridBoundColumn DataField="DocumentID" HeaderText="Document ID" />
<telerik:GridBoundColumn DataField="Description" HeaderText="Description" />
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="true" />
<ClientEvents OnRowDblClick="RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Code Behind
protected void _radgrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
Fill_radgrid();
}
private void Fill_radgrid(bool dataBind = false)
{
//Data Manager is a class that I built that makes all of the Database calls. It returns a DataSet
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text, _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
if (dataBind)
_grdNegativeAck.DataBind();
}
protected void _radgrid_OnItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
//If the current user is authorized to resolve, show the Resolve button on the grid
if (currentUser.IsAuthorized))
{
GridCommandItem cmditem = (GridCommandItem)e.Item;
Button _btnResolve = (Button)cmditem.FindControl("_btnResolve");
_btnResolve.Visible = true;
_grdNegativeAck.MasterTableView.GetColumn("CheckboxSelectColumn").Visible = true;
}
}
else if (e.Item is GridDataItem)
{
//If the record is already resolved, do not show the checkbox on the side and color the record green
GridDataItem GDItem = e.Item as GridDataItem;
if (GDItem["Resolved"].Text.ToUpper() == "TRUE")
{
((e.Item as GridDataItem)["CheckboxSelectColumn"].Controls[0] as CheckBox).Visible = false;
(e.Item as GridDataItem).BackColor = System.Drawing.Color.Green;
}
}
}
Here's where things get interesting. On my localhost, when using the same database, I get 0 records returned. I checked the DataSet that I'm binding to, and there is literally 0 rows. When I query the database, I get 185 records no problem. I double-checked the parameters I pass to the query, and they're the same. When I put this same code on the Test site, the page will get 184 records... when it should be matching exactly and get 185 records.
The other page doesn't get any records on either my localhost or my test site.
I'm really at my wit's end here. Anyone encounter a similar situation or have somewhere they can point me?
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
In the above line, you are missing a comma(,) after txtBoxDocumentType.Text.
Hope this will resolve your problem.
I am getting this error while clicking the edit button on my asp.net gridview.
'ddldept' has a SelectedValue which is invalid because it does not exist in the list of items.
This is my dropdown's SelectedIndexChanged event
protected void dgbus_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = dgbus.SelectedRow;
//here am getting the error
ddldept.SelectedValue = row.Cells[2].Text.ToString().Trim();
txtappcode1.Text = row.Cells[3].Text.ToString();
txtappcode2.Text = row.Cells[4].Text.ToString();
hdn.Value = row.Cells[1].Text.ToString();
lblMsg.Text = "";
}
eveything is working fine, but when I try to edit a row having row.Cells[2].Text as 'Finance & Accounts'..
Is this '&' a problem?
My Gridview markup
<asp:GridView ID="dgbus" runat="server" class="table-format"
AutoGenerateColumns="False" Width="100%"
OnSelectedIndexChanged="dgbus_SelectedIndexChanged"
OnRowCreated = "dgbus_RowCreated"
OnPageIndexChanging = "dgbus_PageIndexChanging" AllowPaging="True"
PageSize="50">
<Columns>
<asp:CommandField ButtonType="Image" HeaderText="Edit Details"
SelectImageUrl="~/images/modify.gif"
SelectText="Modify Approver"
ShowSelectButton="True" />
<asp:BoundField HeaderText="Approver ID" DataField="appid"/>
<asp:BoundField HeaderText="Deptt" DataField="deptt" />
<asp:BoundField HeaderText="Appcode1" DataField="appcode1" />
<asp:BoundField HeaderText="Appcode1" DataField="appcode2" />
</Columns>
<RowStyle CssClass="misctext" Height="20px" />
<HeaderStyle BackColor="ControlLight" CssClass="contentbold"
Height="20px" />
<PagerSettings PageButtonCount="5" />
<PagerStyle BackColor="Gainsboro" CssClass="link" HorizontalAlign="Right"
VerticalAlign="Middle" />
</asp:GridView>
Attempt to find the value in the drop down list before attempting to set the SelectedValue, like this:
if (ddldept.Items.FindByValue(row.Cells[2].Text.ToString().Trim()) != null)
{
ddldept.SelectedValue = row.Cells[2].Text.ToString().Trim();
}
So your full code should be this:
protected void dgbus_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = dgbus.SelectedRow;
if (ddldept.Items.FindByValue(row.Cells[2].Text.ToString().Trim()) != null)
{
ddldept.SelectedValue = row.Cells[2].Text.ToString().Trim();
}
txtappcode1.Text = row.Cells[3].Text.ToString();
txtappcode2.Text = row.Cells[4].Text.ToString();
hdn.Value = row.Cells[1].Text.ToString();
lblMsg.Text = "";
}
I have gridview with 4 columns; in column 1 I added a place holder and other 3 columns are boundfields. In column 1 I'm adding radio buttons dynamically using html code by which I am able to select only one radio button. It's working well, but the problem is I am unable to find the radio button control when a button outside of the gridview is clicked.
Please help, I've been stuck on this problem for 4 days.
Thank you in advance.
I used the following code
.aspx File
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" ForeColor="Black" GridLines="Vertical"
onrowdatabound="GridView1_RowDataBound"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="FIRST NAME" DataField="FNAME"/>
<asp:BoundField HeaderText="LAST NAME" DataField="LNAME"/>
<asp:BoundField HeaderText="EMAIL" DataField="EMAIL"/>
<asp:BoundField HeaderText="AGE" DataField="AGE"/>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:Button ID="btnSave" Text="Save" runat="server" onclick="btnSave_Click1" />
</form>
Code Behind file
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1 && e.Row.DataItem != null)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
RadioButton rb = new RadioButton();
rb.ID = "rbSelect";
holder.Controls.Add(rb);
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
PlaceHolder holder = (PlaceHolder)GridView1.Rows[i].Cells[0].FindControl("ph");
RadioButton rbtn = holder.FindControl("rb") as RadioButton;
if (rbtn.Checked == true)
{
Response.Write("<Script>alert('Radiocheck')</Script>");
}
}
}
It's not clear why you need to create dynamic RadioButtons at all. That makes all just more difficult without a benefit in this case(even if, a nested Repeater or GridView would be easier).
However,
you should not create dynamic controls in RowDataBound since that is triggered only if the GridView was databound. But since by default ViewState is enabled you wouldn't DataBind it on postbacks. Dynamic controls on the other hand must be recreated on every postback.
Therefore create them in RowCreated which is triggered on every postback. But note that you have (of course) no DataItem there since it is null at this stage(even if the grid will be databound).
So you should create cynamic controls in RowCreated but load them from RowDataBound where you can also access them (f.e. via FindControl).
But instead of adding html-control like <input type='radio' you should create and add a RadioButton with an id. Otherwise you won't be able to acess it later, so holder.FindControl("rb") will, be null since it's not a server-control.
Here's the complete modified code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
var rb = new RadioButton();
rb.ID = "RbSample";
rb.Text = "rb";
holder.Controls.Add(rb);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var rb = (RadioButton)e.Row.FindControl("RbSample");
rb.Checked = row.Field<bool>("SampleActive");
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rbtn = (RadioButton)GridView1.Rows[i].FindControl("RbSample");
if (rbtn.Checked)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Radiocheck');", true);
}
}
}
It looks like you are doing FindControl with the "value" of the input, but not with the ASP.NET ID of the control, because it has none. Because it's not an ASP.NET control you cannot find it with FindControl.
I also don't know if you can loop through the Controls property of holder, because it's a plain html control. But you can try it out to put a breakpoint on the FindControl line and explore the Controls property of holder.
I have Gridview with some records (1 record=1 row).
On every row I added a button to delete this record from my mysql db.
Every row has the same button.
The problem is I need to know in which row the button was clicked? I need this to get a row index to get id of my record which is in that row.
How can I do this in easiest way?
Gridview:
<asp:GridView ID="GridView1" runat="server"
CellPadding="6" EnableModelValidation="True" ForeColor="#333333"
GridLines="None" Caption="TWOJE WIZYTY" Font-Bold="True"
onrowcreated="GridView1_RowCreated" style="text-align: left">
<AlternatingRowStyle BackColor="#AEAEAE" />
<EditRowStyle BackColor="Blue" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#868686" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="Blue" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#C7C7C7" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
</asp:GridView>
The button is being added like that:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
Button b1 = new Button();
b1.Text = "usuĊ";
b1.OnClientClick = "return potwierdzenie()";
b1.Click+=new EventHandler(b1_Click);
TableCell cel = new TableCell();
cel.Width = Unit.Pixel(180);
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[2].Text = "";
e.Row.Cells.Add(cel);
}
else
{
//HERE IS MY BUTTON ADDED! *********************
cel.Controls.Add(b1);
cel.HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
e.Row.Cells.Add(cel);
}
}
You can use the NamingContainer property of your button to get the GridViewRow. Then you have all you need to find your other controls (f.e. the control with ID if you use TemplateFields).
protected void button_Delete_click(Object sender, EventArgs e)
{
Button btn = (Button) sender;
GridViewRow row = (GridViewRow) btn.NamingContainer;
// assuming you store the ID in a Hiddenield:
Hiddenield hiddenID = (HiddenField) row.FindControl("HiddenID");
int ID = int.Parse(hiddenID.Value);
// delete the record
}
You can also get the row-index via row.RowIndex.
I have a grid view with below markup and below datasourse (linq query-stored procedure), I have added delete and update command field, but I do not know what code I have to add until deleting and updating for this grid view works.
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Docid,Transid"
DataNavigateUrlFormatString="~/DocResult.aspx?Docid={0}&TransID={1}"
DataTextField="DocumentNo" HeaderText="Doc" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="transmittal" HeaderText="transmittal" SortExpression="transmittal" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var query = _DataContext.spQuickSearch(txtSearchKeywords.Text);
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
The stored procedure spQuickSearch is like below:
ALTER proc [dbo].[spQuickSearch]
#Searchtext varchar(50)=null
AS
select DocId,TransId,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or TRANSMITTAL like '%'+#SearchText + '%'
You can handle commands like this:
protected void GridViewDocuments_Search_RowCommand(object sender, GridViewCommandEventArgs e)
{
string cmdArg = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Details":
//TODO: handle your Details command...
break;
case "Delete":
//TODO: handle your Delete command...
break;
}
}
You can add as many commands as you want (CommandName property for control). For example you can add another button and set Delete CommandName like this:
<asp:Button ID ="btn_Delete" Text="Delete" runat= "server" CommandName= "Delete" CommandArgument='<%#
Container.DataItemIndex%>' />
After command is completed you can call DataBind to refresh grid:
GridViewDocuments_Search.DataBind();
check this example
http://www.vkinfotek.com/gridview/gridview-commandfield.html
for detail
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.commandfield.showeditbutton.aspx