HyperLink to specific item in gridview row - c#

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;
}
}
}

Related

Passing gridview row data to textboxes on selection of gridview row

I can't seem to make data from my gridview pass to textboxes outside of my gridview on row selection. The event seems to be firing, but the textboxes are always filled with & nbsp;. I can't figure out why this is happening since none of the cells in the gridview are blank. I have been researching this problem for a few days, on this site and other sites, with no luck. Here is the piece of my aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtBLName.Text = GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text;
}
Here is my gridview code:
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
</asp:GridView>
Can someone please help? Thanks!
It's Working
ASP CODE
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView2"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
DataTable oDT = new DataTable();
oDT.Columns.Add("edit",typeof(string));
oDT.Columns.Add("LastName", typeof(string));
oDT.Rows.Add("ad", "1212121");
oDT.Rows.Add("aad", "1asdasd212121");
GridView2.DataSource = oDT;
GridView2.DataBind();
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
TextBox1.Text = row.Cells[1].Text;
}
RESULT

Dynamic link in asp.net gridview

I'm trying to create a gridview with an extra column that contains a hyperlink for each row. Unfortunately my hyperlinks doesn't start from the top of the column, instead they are started from the second row of the hyperlink's column.
See this picture for more information >>> http://i.imgur.com/TLsVo5s.png
As you can see in that picture, there is a 'view' column that contains hyperlinks, but the problem is the first row is always empty. The hyperlink that's on the second row should be on the first, and the third should be on the second, and so on.
Can anyone show me where I went wrong?
Here is my gridview declaration on my aspx page:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting" PageSize="20" DataKeyNames="no_kwitansi"
DataSourceID="home1" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" RowStyle-Wrap="False" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<RowStyle HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
<Columns>
<asp:BoundField HeaderText="#" />
<asp:BoundField DataField="no_kwitansi" HeaderText="No.Kwitansi" SortExpression="no_kwitansi" ReadOnly="True" />
<asp:BoundField DataField="nama_vendor" HeaderText="Vendor" SortExpression="nama_vendor" />
<asp:BoundField DataField="nama_pekerja" HeaderText="Pekerja" SortExpression="nama_pekerja" />
<asp:BoundField DataField="nama_penanggungjawab" HeaderText="Penanggungjawab" SortExpression="nama_penanggungjawab" />
<asp:BoundField DataField="satuan" HeaderText="Satuan" SortExpression="satuan" />
<asp:BoundField DataField="jumlah" HeaderText="Nominal" SortExpression="jumlah" />
<asp:BoundField DataField="tanggal" HeaderText="Tanggal" SortExpression="tanggal" />
</Columns>
</asp:GridView>
Here is my C# code behind:
This is my page_load function, I created the template field here.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["SortExpr"] = Sort_Direction;
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
home1.DataBind();
}
}
Here is my gridview rowDataBound function, where I create the hyperlink.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
hlContro.NavigateUrl = "./Home.aspx?ID=" + GridView1.Rows[i].Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
}
e.Row.Cells[8].Controls.Add(hlContro);
}
}
so why not just a template field, and remove all the server side boilerplate? What happen if you would change position of your column?
Below is the solution where you need not to write anything in your server side code. Simple and easy.
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("no_kwitansi") %>'
NavigateUrl= '<%# "./Home.aspx?ID=" + Eval("no_kwitansi") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.
Just write code like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
hlContro.NavigateUrl = "./Home.aspx?ID=" + e.Row.Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
e.Row.Cells[8].Controls.Add(hlContro);
}
}
why are you adding it from code behind even you can add in html page
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="test1" runat="server" ForeColor="#525252" Text="Documents" />
</ItemTemplate>
</asp:TemplateField>
a similar example is shown on this link you can try Link

Enable Linkbutton in Gridview when ASP.NET Button Clicked

I have a gridview that displays a record with some linkbuttons.
What I want is when my ASP.NET ButtonStart is clicked enable the LinkButton in the Gridview
<asp:GridView ID="gvData" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="688px" AllowPaging="True" AllowSorting="True"AutoGenerateColumns="False"
OnRowCommand="gvData_RowCommand"
OnRowDataBound="gvData_RowDataBound">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" SortExpression="Id">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Received" HeaderText="Received" SortExpression="Received"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbClose" runat="server" CausesValidation="False" CommandName="CloseClicked"
OnClick="CloseClick_Click">Close</asp:LinkButton>
</ItemTemplate>
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:button runat="server" text="Start" ID="btnStart" />
I know how to disable it in RowDataBound.
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbClose = (LinkButton)e.Row.Cells[5].FindControl("lbClose");
if (lbClose == null)
{
return;
}
var lblReceive = (Label)e.Row.FindControl("lblReceive ");
if (lblReceive .Text == "" && !IsPostBack)
{
lbClose.Enabled = true;
lbEdit.Enabled = true;
lbDelete.Enabled = true;
}
}
}
I believe you have to call RowDataBound from the BtnStart Click event but am not sure.
protected void btnStartTrans_Click(object sender, EventArgs e)
{
//Enable lblClose in gridview
}
Just loop through the rows in the grid view and enable the lbClose in each row, like this:
protected void btnStartTrans_Click(object sender, EventArgs e)
{
// Loop through all rows in the grid
foreach (GridViewRow row in grid.Rows)
{
// Only look for `lbClose` in data rows, ignore header and footer rows, etc.
if (row.RowType == DataControlRowType.DataRow)
{
// Find the `lbClose` LinkButton control in the row
LinkButton theLinkButton = (LinkButton)row.FindControl("lbClose");
// Make sure control is not null
if(theLinkButton != null)
{
// Enable the link button
theLinkButton.Enabled = true;
}
}
}
}

Issue with getting CheckBox value in GridView

I have a GridView that contains a CheckBox control. Once the users check the rows that they want, they click a button and I have to update the database for each checked row.
I have the code to iterate trough the gridview rows and look at the checkbox value, but its always false, even if its checked. I do get a reference to the checkbox in ignore but it is always false. What am I missing here?
aspx.cs file:
protected void Ignore_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdNotReceived.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ignore = (CheckBox)row.FindControl("chkIgnore");
if (ignore.Checked)
{
// Update Database
}
}
}
}
.aspx page:
<asp:GridView ID="grdNotReceived" runat="server"
Width="600px"
CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
PagerStyle-CssClass="pgr" AutoGenerateColumns="false">
<AlternatingRowStyle CssClass="alt"/>
<Columns>
<asp:BoundField DataField="Store" HeaderText="Store" />
<asp:BoundField DataField="Dept" HeaderText="Dept" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="RefNumber" HeaderText="RefNumber" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Vendor" HeaderText="Vendor" />
<asp:BoundField DataField="Total" HeaderText="Total" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView databind method:
protected void LoadExceptions()
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
If your databinding function ( LoadExceptions() ) is being called somwhere on the page load (like the Load event or class constructor) then it's overriding the changes the user has made in the form.
Don't databind if the page is in post back, you can add an if (!Page.IsPostBack) before calling LoadExceptions() or you can update LoadExceptions() to check it:
protected void LoadExceptions()
{
if (!Page.IsPostBack)
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
}

nested gridview get parent row

I am using Nested GridViews where each row in the gridview has child gridView.
I am using RowDataBound Event of Parent GridView, to Binding Child GridView.
My Problem is that, how to get Parent GridView's Key on Child gridViews RowDataBound Event.
Below is example code:
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="1" AllowPaging="true" PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" SkinID="GVCenter" onrowdatabound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the code behind:
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvChild= (GridView)e.Row.FindControl("gvChild");
gvChild.DataSource = getChildObj();
gvChild.DataBind();
}
}
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Here I need to get the parent gridview Row Key
}
}
Hope the above code explains all the scenario.
Thanks in advance
Sandy
Try this
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="10" AllowPaging="true"
PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" OnRowDataBound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HdnID" runat="server" Value='<%# Eval("ID") %>' />
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false"
ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvChild = (GridView)e.Row.FindControl("gvChild");
gvChild.DataSource = GetData();
gvChild.DataBind();
}
}
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = ((HiddenField)e.Row.Parent.Parent.Parent.FindControl("HdnID")).Value;
}
}
I don't think you will be able to track it normally, but I would embed ID field into the hidden field and put this hidden field under TemplateField,
<ItemTemplate>
<asp:HiddenField ID="idOfYourHiddenField" runat="server" Value='<%# Eval("ID") %>' />
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
this way you can get its value by going
gvChild.Parent.FindControl("idOfYourHiddenField");
You Can Access The Parent of Child Gridview with the Parent Property.
You must be Try This:
GridView gvChild = (GridView)e.Row.FindControl("gvChild");
Response.Write(gvChild.Parent);
You have to go 4 steps back and get the parent row like this
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvMasterRow = (GridViewRow)e.Row.Parent.Parent.Parent.Parent;
}
}
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="1" AllowPaging="true"
PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" SkinID="GVCenter"
OnRowDataBound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false"
ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# (((IDataItemContainer)Container.Parent.Parent.Parent).DataItem as MyClass).MyProperty %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>

Categories

Resources