Container.DisplayIndex not working with paging in ASP.NET - c#

I have a gridview that is bound with data from code behind. Paging is applied in gridview. Everything works fine. For showing Row-Index i use Container.DisplayIndex.
When i go to next page through paging, every time gridview bind perfectly but DisplayIndex start with 1 to pagesize. I don't know what is wrong with the code.
Here is Asp.NET Code:
<asp:GridView runat="server" ID="dlAddress" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="dlAddress_PageIndexChanging" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DisplayIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Center"/>
</asp:GridView>
C# Code:
public void bindGridView()
{
DBACon.Open();
SqlCommand Cmd = new SqlCommand("getAddresses", DBACon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(DS);
dlAddress.DataSource = DS;
dlAddress.DataBind();
}
protected void dlAddress_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dlAddress.PageIndex = e.NewPageIndex;
bindGridView();
}

Here,
ASPX:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="False" DataKeyNames="AddressID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="RowNumber">
<ItemTemplate>
<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Related

Dropdownlist displaying two gridviews

I currently have a drop down list that on selected index changed it displays data in a GridView based of the value of the drop down list. However, it is displaying the data in the existing GridView and then displaying another gridview next to the existing one with the exact information. I am just trying to display the data in the existing open.
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=
(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
con.Open();
SqlDataAdapter DataAdapter = new SqlDataAdapter(string.Format("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = '" + DropDownList1.SelectedValue + "'"), con);
DataAdapter.Fill(table);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
Existing Gridview:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="Item ID" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemIDAdmin" Text='<%# Eval("ItemID")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemDescAdmin" Text='<%# Eval("ItemDesc")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="barQuantityAdmin" Text='<%# Eval("BarQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="storageQuantityAdmin" Text='<%# Eval("StorageQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

How to create hyper links on rows of gridview that is derived from database in asp.net?

I m making a website in which i have used grid view table and retrieved data from database table category as shown down :
Database table category
I want to create link on rows i.e family tours ,religious tour ,Adventure Tours,Special Event Tours,National Park and whenever new row is created in table hyperlink should be created automatically on it .... How should I do it Please do help .... thank you
I want create link on data that is inside the red mark
Try this, I develop for you:
.aspx
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Page
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("page") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Navigation
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdn_navigation" Value='<%# Bind("navigation") %>' runat="server" />
<asp:LinkButton ID="LinkButton1" CommandName="navigation" runat="server">Click Me</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind .cs:
private void load_gridView()
{
DataTable dt = new DataTable();
dt.Columns.Add("page");
dt.Columns.Add("navigation");
DataRow dr = dt.NewRow();
dr["page"] = "family tours";
dr["navigation"] = "family_tours.aspx";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2["page"] = "religious tour";
dr2["navigation"] = "religious_tour.aspx";
dt.Rows.Add(dr2);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
HiddenField hdn_navigation = (HiddenField)row.FindControl("hdn_navigation");
if (e.CommandName.ToString() == "navigation")
{
Response.Redirect(hdn_navigation.Value);
}
}
calling function from Page_Load():
protected void Page_Load(object sender, EventArgs e)
{
load_gridView();
}
Thank you for your help really appreciate your help #Rana Ali
I have got a more simplified method that can be done by just writing this code I hope this will help others as well :)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" GridLines="None" Height="300px"
Width="100px">
<Columns>
<asp:BoundField DataField="Cat_name" HeaderText="Category"
SortExpression="Cat_name" >
<HeaderStyle Font-Bold="True" Font-Italic="True"
Font-Names="Lucida Calligraphy" Font-Size="X-Large" ForeColor="#3399FF" />
<ItemStyle Font-Bold="True" Font-Italic="True" Font-Size="Small" />
</asp:BoundField>
<asp:HyperLinkField DataTextFormatString="View" DataTextField="Cat_url" DataNavigateUrlFields="Cat_url" HeaderText="" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ToursandTravelsConnectionString %>"
SelectCommand="SELECT [Cat_name], [Cat_url] FROM [category]">
This is and output of the code above :

Create gridview datatable/source code behind error

On my page, there are two gridviews where data are added to them dynamically using code behind. There are no problems with the code as far as I can see, the first gridview runs fine, but as soon as I want to add data to the second it gives me the error of:
Column 'LabourType' does not belong to table Table1
This is the error it gives when I initialize the labour grid first (Everything goes through fine). However, if I initialize the PartsGrid first it gives me the same error, just with the first column name of the parts grid.
This is what I have done in the Page_Load:
DataTable dtParts;
DataTable dtLabour;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateCustomers();
dtLabour = new DataTable();
MakeDataTableLabour();
EmptyDataStringLabour();
this.gvLabour.EditIndex = -1;
dtParts = new DataTable();
MakeDataTableParts();
EmptyDataStringParts();
this.gvParts.EditIndex = -1;
}
else
{
dtLabour = (DataTable)ViewState["DataTable"];
dtParts = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dtLabour;
ViewState["DataTable"] = dtParts;
}
Can anybody please tell me if I am doing anything wrong? Or how can I solve this to allow both grids for data to be added dynamically? Thanks in advance
EDIT - More Data
For the Parts Grid this is how I create and add data to the datatable:
private void MakeDataTableParts()
{
dtParts.Columns.Add("Units");
dtParts.Columns.Add("PartNo");
dtParts.Columns.Add("Description");
dtParts.Columns.Add("CostPrice");
}
private void AddToDataTableParts()
{
DataRow drParts = dtParts.NewRow();
drParts["Units"] = txtUnits.Text.Trim();
drParts["PartNo"] = txtPartNo.Text.Trim();
drParts["Description"] = txtDescription.Text.Trim();
drParts["CostPrice"] = txtCostPrice.Text.Trim();
dtParts.Rows.Add(drParts);
}
private void BindGridParts()
{
gvParts.DataSource = dtParts;
gvParts.DataBind();
}
And for the labour:
private void MakeDataTableLabour()
{
dtLabour.Columns.Add("Units");
dtLabour.Columns.Add("LabourType");
dtLabour.Columns.Add("LabourCost");
}
private void AddToDataTableLabour()
{
DataRow drLabour = dtLabour.NewRow();
drLabour["Units"] = txtLabourUnits.Text;
drLabour["LabourType"] = lstLabourType.SelectedValue.ToString();
drLabour["LabourCost"] = txtLabourCost.Text;
dtLabour.Rows.Add(drLabour);
}
private void BindGridLabour()
{
gvLabour.DataSource = dtLabour;
gvLabour.DataBind();
}
This is how my gridviews are created in .aspx
Parts:
<asp:GridView ID="gvParts" runat="server" AutoGenerateColumns="true" CellPadding="8" CellSpacing="8" AllowPaging="false"
Width="100%" OnPageIndexChanging="gvParts_PageIndexChanging" OnRowCommand="gvParts_RowCommand"
OnRowCancelingEdit="gvParts_RowCancelingEdit" OnRowEditing="gvParts_RowEditing"
OnRowUpdating="gvParts_RowUpdating" OnRowDeleting="gvParts_RowDeleting" >
<emptydatatemplate>
There are currently no parts listed.
</emptydatatemplate>
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEditParts" runat="server"CommandName="EditParts" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkRemoveParts" runat="server" CommandName="DeleteParts" CommandArgument='<%# Container.DataItemIndex %>'>Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="Grid" />
<RowStyle CssClass="rowStyle" />
<AlternatingRowStyle CssClass="alt" />
<PagerStyle CssClass="pgr" />
</asp:GridView>
Labour:
<asp:GridView ID="gvLabour" runat="server" AutoGenerateColumns="true" CellPadding="8" CellSpacing="8" AllowPaging="false"
Width="100%" OnPageIndexChanging="gvLabour_PageIndexChanging" OnRowCommand="gvLabour_RowCommand"
OnRowCancelingEdit="gvLabour_RowCancelingEdit" OnRowEditing="gvLabour_RowEditing"
OnRowUpdating="gvLabour_RowUpdating" OnRowDeleting="gvLabour_RowDeleting" >
<emptydatatemplate>
There are currently no labour listed.
</emptydatatemplate>
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEditLabour" runat="server"CommandName="EditLabour" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkRemoveLabour" runat="server" CommandName="DeleteLabour" CommandArgument='<%# Container.DataItemIndex %>'>Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="Grid" />
<RowStyle CssClass="rowStyle" />
<AlternatingRowStyle CssClass="alt" />
<PagerStyle CssClass="pgr" />
</asp:GridView>
I'm binding the grids on the button click events (modal popop) as follows:
protected void btnSubmitPart_Click(object sender, EventArgs e)
{
AddToDataTableParts();
BindGridParts();
ClearPartsToAddNewItem();
}
protected void btnSubmitLabour_Click(object sender, EventArgs e)
{
AddToDataTableLabour();
BindGridLabour();
ClearLabourToAddNewItem();
}
Error is self explanatory. You have set column LabourType either as DataField or used this column in databing expression in one of your GridView but this column is not present in DataSource.

How to bind 2 databse tables to gridview and one as dropdown

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="301px" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
<%-- <asp:BoundField DataField="StudentDOB" HeaderText="StudentDOB" SortExpression="StudentDOB" />--%>
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/Employee/EmployeeEditPage.aspx?StudentID={0}", Eval("StudentID"))%>'> Edit</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
above is my design:
below I wrote my code for to display the database, which have table departmenttable and another table studenttable to show the values into the grid. in department table I have departmentname(dept_name)
which should come in dropdown inside the gridview..but it showing error..pls help..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(DataBase.GetConnection());
con.Open();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList = (DropDownList)e.Row.FindControl("dept_name");
//bind dropdownlist
DataTable dt = con.GetData("select dept_name from dbo.DepartmentTable");
ddList.DataSource = dt;
ddList.DataTextField = "dept_name";
ddList.DataValueField = "DeptName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["DeptName"].ToString();
con.Close();
GridView1.DataBind();
}
}
}
For binding dropdownlist in GriView first you need to find it by its id. In your sample code, you are trying to find something which is not dropdownlist.
Try this,
DropDownList ddList = (e.Row.FindControl("DropDownList1") as DropDownList);
if(ddList != null)
{
//your code
}

Hyperlink a column with relative path value of another column in mysql database

I am an extreme beginner and have done quite a bit of searching on this with not much success-- and am not sure if this even possible/makes sense: I am trying to create a job board database and webpage with links to the respective pages of the jobs. I have a gridview in mySQL and ASP.net with Job Title, Date, and relative link/path to pages with further description of the jobs. I'd like to make the Job Title hyperlinked using the relative path from the Link column (hopefully just scripted to generate the full link-- not hard coded for each row). When this page is running, the Link column will most likely be hidden. This is so that the user can edit the link column if anything changes, and not have to edit the code much, if at all.
[Job Title] [Date Posted] [Link]
Job 1 June, 2012 /california/job1.asp
Job 2 August, 2012 /newyork/job2.asp
etc..
I would like to be displayed in the browser:
Job Title Date Posted
[Job 1][1] June, 2012
[Job 2][2] August, 2012
Here's the asp code for the table, I know I need a hyperlinkfield or column for Job Title with a navigateurl. But don't know how to connect the two table columns I have above. I'd appreciate any help I can get :)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Job Postings
</h2>
<p>
The following are the current open positions:
</p>
<p>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display." BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="JobTitle" HeaderText="JobTitle"
SortExpression="JobTitle" />
<asp:BoundField DataField="JobDatePosted" HeaderText="JobDatePosted"
SortExpression="JobDatePosted" DataFormatString="{0:d}" />
<asp:BoundField DataField="JobLink" HeaderText="JobLink"
SortExpression="JobLink" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [JobTitle], [JobDatePosted], [JobLink] FROM [jobpostings]">
</asp:SqlDataSource>
</p>
</asp:Content>
If this is a dumb idea, please let me know a better way of doing it?
Best practise is using ItemTemplate something like this
Add hyperlink control and set/edit/update value programatically. Add editTemplate for editing purpose.
Design.aspx: (Tested code)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="JobTitle">
<ItemTemplate>
<asp:HyperLink ID="jobTitle" Text='<%# Bind("JobTitle") %>' NavigateUrl='<%# Bind("JobLink") %>' runat="server"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post Date">
<ItemTemplate>
<asp:Label ID="lbldatepost" runat="server" Text='<%# Bind("JobDatePosted","{0:dd MMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="lblLink" runat="server" Text='<%# Bind("JobLink") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtesetLink" runat="server" Text='<%# Bind("JobLink") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvBind();
}
}
public void gvBind()
{
SqlDataAdapter dap = new SqlDataAdapter("SELECT id, [JobTitle], [JobDatePosted], [JobLink] FROM [jobpostings]", con);
DataSet ds = new System.Data.DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gvBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtlink = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtesetLink");
Label lblid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblid");
int result = UpdateQuery(txtlink.Text, lblid.Text);
if (result > 0)
{
//lblmsg.text = "Record updated";
Response.Write("Record updated");
}
GridView1.EditIndex = -1;
gvBind();
}
public int UpdateQuery(string setlink,string id)
{
SqlCommand cmd=new SqlCommand("update jobpostings set JobLink='"+setlink+"' where id='"+id+"'",con);
con.Open();
int temp = cmd.ExecuteNonQuery();
con.Close();
return temp;
}
Note: Hope it almost solved your problem, let me now if any issue.
you can try with this code
<asp:HyperLinkField
DataNavigateUrlFields=""
DataNavigateUrlFormatString="....aspx?id={0}"
DataTextField="
NavigateUrl="" />
Link : http://msdn.microsoft.com/fr-fr/library/zt9c22bx%28v=vs.80%29

Categories