paging in gridview from dataset - c#

i have a datset that i save into viewstate and i want to paging on that dataset.
Code for bind gridview
DataSet _ds = _fOrderInvoice.ExecuteDataSet();
ViewState["FIOrders"] = _ds.Tables[0];
grdInvoiced.DataSource = _ds; // bind the gridview
Now i want paging on the gridview. So how can i do that from the dataset that i have save into my ViewState["FIOrders"]. My gridview is below
<asp:GridView ID="grdInvoiced" runat="server" Width="100%" ViewStateMode="Enabled" DefaultSortColumnName="OrderNo" OnSelectedIndexChanged="GridInvoice_SelectedIndexChanged" AutoGenerateColumns="False" OnSorting="invoice_sorting" OnRowDataBound="grdInvoice_Rowdatabount" ShowFooter="true" PageSize="20" AllowPaging="True" AllowSorting="True" DataKeyNames="OrderNo" ExcelExportFileName="Export_AccountTerms.xls"
ShowHeaderWhenEmpty="true" OnPageIndexChanging="grdInvoiced_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="View" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="rbtnSelect" GroupName="a" runat="server" />
<asp:Literal ID="ltOrder" runat="server" Text='<%# Eval("OrderNo")%>' Visible="false"></asp:Literal>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" Width="50px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
PageIndexChanging event
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex+1;
if (ViewState["FOrders"] != null)
{
DataTable ds = (DataTable)ViewState["FIOrders"];
grdInvoiced.PageIndex = e.NewPageIndex + 1;
// Collection<FinalizedOrderInvoiceRows> _rows = ViewState["FIOrders"] as Collection<FinalizedOrderInvoiceRows>;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}

Convert Your ViewState into DataSet and Bind it to GridView
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex;
if (ViewState["FOrders"] != null)
{
DataSet ds =(DataSet) ViewState["FIOrders"] ;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}

Related

displaying images from a folder in a gridView ASP.NET

How can I display images in GridView from a folder in my project?
Iv'e tried to create an image/imageField dynamically, but it didn't work- I don't know how to connect the images to the imageField in my GridView, and that's my main problem.
How can I do it?
Here's my GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:ImageField HeaderText="image">
</asp:ImageField>
</Columns>
</asp:GridView>
(In addition, it's okay to use imageField at all?)
And here's my Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].Cells[3].Text == "not read")
{
//here i want to display image whose url is: "/images/notRead.png"
}
else
{
//here i want to display image whose url is: "/images/read.png"
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Thanks(:
The image url is not in the dataset so can change your GridView definition to
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<asp:Image runat="server" ID="img" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Change your page load to
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Add following
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var image = e.Row.FindControl("img") as Image;
image.ImageUrl = e.Row.Cells[3].Text == "not read" ? "/images/notRead.png" : "/images/read.png";
}
}
This should accomplish what you are trying to do.

Getting data from gridview to textbox in asp.net c# using link button

Here is my aspx.cs page code. Every time when I run the code the only answer I get is: Column name doesn't exist.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="table table-striped table-bordered table-hover" >
<Columns>
<asp:BoundField DataField="TutorialId" HeaderText="Tutorial Id"/>
<asp:BoundField DataField="TutorialTitle" HeaderText="TutorialTitle"/>
<asp:BoundField DataField="CatId" HeaderText="Category Id" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" OnClick="lnk_OnClick"
CommandArgument='<%#Eval("TutorialId") %>'>View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my aspx code. Here I have used click event on the link
button which is getting the ID number:
protected void lnk_OnClick(object sender, EventArgs e)
{
int TutorialId = Convert.ToInt32((sender as LinkButton).CommandArgument);
GetTutorialById();
}
private void GetTutorialById()
{
OnlineSubjects onlinesubject = new OnlineSubjects();
DataTable dTable = onlinesubject.GetTutorialById();
txtTutId.Text = dTable.Rows[0]["TutorialId"].ToString();
txtTitle.Text = dTable.Rows[0]["TutorialTitle"].ToString();
txtAddTutorial.Text = dTable.Rows[0]["TutorialDesc"].ToString();
}
public DataTable GetTutorialById()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter(
"#TutorialId", TutorialId, System.Data.SqlDbType.Int, 100);
DataTable dTable = DataLayer.DataAccess.ExecuteDTByProcedure(
"spTutorialViewById", parameters);
return dTable;
}

How to bind data in checkbox list in Gridview with same datatable?

I want to give checkbox list in Gridview. How can I bind data to checkbox list from same data table?
What i understood that i am showing let me know you are asking for the same or not
This is the design portion
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="gridview"
>
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="name" runat="server" Text='<%#Eval("Name")%>'>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No">
<ItemTemplate>
<asp:Label ID="rollno" runat="server" Text='<%#Eval("Roll_No")%>'>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:CheckBox runat="server" Text='<%#Eval("Gender")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
Here I have made a temoporary data table you can make data table through database also
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
check_box();
}
}
public void check_box() {
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Roll_NO");
dt.Columns.Add("Gender");
dt.Rows.Add();
dt.Rows[0][0]="Prateek Ghosh";
dt.Rows[0][1] = 123;
dt.Rows[0][2] = "Male";
dt.Rows.Add();
dt.Rows[1][0] = "Rahul";
dt.Rows[1][1] = 1234;
dt.Rows[1][2] = "Male";
dt.Rows.Add();
dt.Rows[2][0] = "Neha";
dt.Rows[2][1] = 12345;
dt.Rows[2][2] = "Female";
GridView1.DataSource = dt;
GridView1.DataBind();
}

HyperLink to specific item in gridview row

So I am working on a basketball website. There is a gridview full of teams and what I would like is when you click on a team name, it links you to a new page that has info about the team. What I tried so far only links every team to the same details page.
Here is my gridview code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Team"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"
Height="340px" Width="776px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Rank" DataNavigateUrlFormatString="~/MemberPages/Details.aspx?Rank={0}"
HeaderText="Team" SortExpression="Team" ItemStyle-Width = "150" >
<ItemStyle Width="150px"></ItemStyle>
</asp:HyperLinkField>
<asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" />
<asp:BoundField DataField="PointsPerGame" HeaderText="PointsPerGame"
SortExpression="PointsPerGame" />
<asp:BoundField DataField="OpponentPointsPerGame"
HeaderText="OpponentPointsPerGame" SortExpression="OpponentPointsPerGame" />
<asp:BoundField DataField="TopPlayer" HeaderText="TopPlayer"
SortExpression="TopPlayer" />
</Columns>
</asp:GridView>
And here is what I tried in the cs file to databind them to a specific link:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Team"),new DataColumn("Ranking"), new DataColumn("PointsPerGame"),
new DataColumn("OpponentPointsPerGame"), new DataColumn("TopPlayer")});
GridView1.DataBind();
}
}
For that kind of show/hide logic on specific row, you will need to use GridView.RowDataBound event.
Use a TemplateField instead of BoundField.
Place HyperLink control inside.
Then retrieve the HyperLink control inside RowDataBound event.
Example Code
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="MyHyperLink" Text="My Text" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(
Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var myHyperLink = e.Row.FindControl("MyHyperLink") as HyperLink;
if(SOME_LOGIC)
{
myHyperLink.Visible = false;
}
}
}

gridview databinding problems

Trying to figure out why I'm having a problem getting GridView1 to databind
HTML:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
CellPadding="10" RowStyle-VerticalAlign="Top"
BackColor="White" BorderColor="Black" BorderWidth="1px" OnRowCreated="GridView1_RowDataBound"
Width="100%" AllowPaging="true" BorderStyle="Solid" PagerSettings-Position="TopAndBottom">
<Columns>
<asp:TemplateField HeaderText="Last" >
<ItemStyle VerticalAlign="Top" />
<ItemTemplate>
<%#Eval("Last")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First" >
<ItemStyle VerticalAlign="Top" />
<ItemTemplate>
<%#Eval("First")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Supervisor ID" >
<ItemStyle VerticalAlign="Top" />
<ItemTemplate>
<%#Eval("supervisorId")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// EdT: if there is no value in session["userId"], redirect user to login page
if ((HttpContext.Current.Session["userId"]) == null)
{
Response.Redirect("Default.aspx");
}
else
{
userName = SqlHelperClass.GetUserName((int)HttpContext.Current.Session["userId"]);
timeCard = new TimeCard((int)HttpContext.Current.Session["userId"], GetCurrentPayPeriod());
// EdT: Set value of literal
Literal1.Text = userName;
// EdT: Set default values for SelectParameters
string userId = HttpContext.Current.Session["userId"].ToString();
string pped = Convert.ToString(GetCurrentPayPeriod());
SqlDataSource1.SelectParameters["user"].DefaultValue = userId;
SqlDataSource1.SelectParameters["pped"].DefaultValue = pped;
}
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// set value of dropdown list in GridView Row to the value contained in the timecard DataTable
if (e.Row.RowType == DataControlRowType.DataRow)
{
string dropDownListValue = CurrentTimeCard.TimeCardDataTable.Columns["projectName"].ToString();
DropDownList dropDownList = (DropDownList)e.Row.FindControl("DropDownList1");
dropDownList.DataSource = SqlDataSource2;
dropDownList.SelectedValue = dropDownListValue;
}
}
SqlDataSource1 markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MinnsTimeDatabase %>"
SelectCommand="spGetTimeCard" SelectCommandType="StoredProcedure" >
<SelectParameters>
<asp:Parameter Name="user" Type="Int32" />
<asp:Parameter DbType="Date" Name="pped" />
</SelectParameters>
</asp:SqlDataSource>
Any thoughts appreciated
You haven't mentioned what your actual problem is, but one issue I see is that you do not need to call DataBind() on a GridView when you are using the DataSourceID property (and thus a datasource control).
So I would definitely remove the call to GridView1.DataBind(); that is the else block of your Page_Load function. Since you are doing processing in the RowDataBound event, it's quite possible that the GridView databinding multiple times during the page life cycle is causing an issue.

Categories

Resources