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
Related
I have a grid view.
<asp:GridView AutoGenerateDeleteButton="false" AutoPostBack="true" OnRowCommand="gwDeleteNAV_RowCommand" OnRowCreated="gwDeleteNAV_OnRowDataBound" OnRowDeleting="DeleteButtonClick" ID="gwDeleteNAV" runat="server" AllowSorting="true" AutoGenerateColumns="False" Width="557px" OnRowDataBound="gwDeleteNAV_OnRowDataBound">
<AlternatingRowStyle BackColor="White" Font-Names="Verdana" Font-Size="Medium" HorizontalAlign="Left" />
<EmptyDataRowStyle BackColor="#EFF3FB" Font-Names="Verdana" Font-Size="Small" HorizontalAlign="Left" />
<rowstyle Height="30px" />
<alternatingrowstyle Height="30px"/>
<HeaderStyle Height="30px" BackColor="#999999" Font-Bold="True" Font-Names="Verdana" Font-Size="10pt"
ForeColor="White" />
<Columns>
<asp:BoundField DataField="Tranid" HeaderText="Id"></asp:BoundField>
<asp:BoundField DataField="FundName" HeaderText="Fund Name"></asp:BoundField>
<asp:BoundField DataField="value" HeaderText="Price"></asp:BoundField>
<asp:BoundField DataField="date" HeaderText="Date"></asp:BoundField><asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" Text="Delete" AutoPostBack="true" OnCommand="lnkDelete_Command" runat="server" OnClientClick="return DeleteConfirmation();"
CommandArgument='<%#Eval("TranId")%>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField></Columns>
<SelectedRowStyle BackColor="#507CD1" />
<PagerStyle BackColor="#999999" />
</asp:GridView>
on server side I am handling link button event as follows:
protected void lnkDelete_Command(object sender, CommandEventArgs e)
{
string transactionid = e.CommandArgument.ToString();
DeleteNAVData(transactionid);
}
Page_Load Event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDropDown();
}
}
Issue I am facing here is, when I click Delete link from UI, It doesn't fire lnkDelete_Command but shows the javascript alert. When I click second time again, It fires the lnkDelete_command Event. any Idea why my code is not calling event at first go.
Regards,
I'm trying to add a Register button to every row in my course gridview so that when the user click on the register button on that particular row, it will register him to that particular course on that row by adding a course registration record into sql.
How should I write my code to insert that row's data into sql?
C#:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
}
ASP.NET:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" Width="394px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="SpeakerName" HeaderText="Speaker" ReadOnly="True" />
<asp:BoundField DataField="startdate" HeaderText="Date" ReadOnly="True" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" />
<asp:TemplateField HeaderText="Button" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="RegButton" runat="server" CausesValidation="false" CommandName="Register"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Register" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" SelectText="Details" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
first you should add course Id (primary key) as datakeynames property to GridView1,and then can get the Id on GridView1_RowCommand like below :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int courseId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
//your other codes
}
so,you have your course Id and by selecting the record you can add current record to sql.hope it helps.
Edit :
also you don't need this part CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" in your aspx page any more
What I need to do is to highlight each row when it is processing to show the process progress, the gridview may contain almost one thousands of row. below is the code I have written but which doesn't work.
Please can someone help me.
<
asp:GridView ID="gdview1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Font-Names="Calibri"
Font-Size="Small" AutoGenerateColumns="False"
OnRowDataBound="gdview1_RowDataBound"
OnSelectedIndexChanged="gdview1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" runat="server" />
</HeaderTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" DataField="ColNUM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row#">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ColNUM" HeaderText="Contract #" />
<asp:BoundField DataField="Col1" HeaderText="Suffix" />
<asp:BoundField DataField="Col2" HeaderText="First Name" />
<asp:BoundField DataField="Col3" HeaderText="Last Name" />
<asp:BoundField DataField="Col4" HeaderText="Street" />
<asp:BoundField DataField="Col5" HeaderText="City" />
<asp:BoundField DataField="Col6" HeaderText="Zip" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butChargeCreditCards_Click(object sender, EventArgs e)
{
DataTable tblContrts = (DataTable) Session["tblContrts"];
foreach (GridViewRow row in gdview1.Rows)
{
CheckBox chkbx = (CheckBox) row.FindControl("chkNUM");
if (chkbx != null && chkbx.Checked)
{
gdview1_SelectedIndexChanged(row,e);
string SS = chkbx.Text.ToString();
string strResults = method1;
}
}
}
protected void gdview1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdview1.Rows)
{
if (row.RowIndex == gdview1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
}
}
}
}
}
Have you tried it by using the "OnRowDataBound" or "OnRowCreated" Event of the Grid and write the color-highliting in code behind?
Something like this?
http://www.java2s.com/Code/ASP/ADO.net-Database/UsingtheRowCreatedEventtoprogrammaticallychangethestyle.htm
But maybe you have a problem because the loading would be too fast to really notice?
I have a gridview with a linkbutton, the url linkbutton is assigned using a code by replacing a key word with a name from the DB.
all works fine, except that when I click the back button in browser and try different link I get this error:
"The HTTP verb POST used to access path '/System.Web.UI.WebControls.Label' is not allowed"
below is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var HyperLink = row.FindControl("LinkButton1") as LinkButton;
var RepID = row.FindControl("Label1") as Label;
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", RepID.Text + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="report_id" DataSourceID="SqlDataSource1" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("report_name")%>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("report_subject")%>'></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
</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>
I think the problem might be that you're doing your binding at the Page_Load stage of the page life cycle. Try moving your foreach code to a
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var HyperLink = e.Row.FindControl("LinkButton1") as LinkButton;
//var RepID = row.FindControl("Label1") as Label;
//You should be able to access your field without referencing the label too
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var myField = row.Field<string>("report_name");
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", myField + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
I have an asp.net page with c# code-behind. I have an event that is triggered in c# when the selected index on a gridview changes... This gridview is bound to an entites-data-source, and I need to find a way to tell my code-behind the id of the object that was selected when it calls the selected_index_changed() method. Any thoughts on how best to do this?
Current event handler code:
protected void VehiclesGridView_SelectedIndexChanged(object sender, EventArgs e)
{
if (ChangeAttemptedId && !IsSavedId)
{
Alert.Show("Dispatch assignment saved... (But you forgot to click Confirm or Cancel!)");
}
IsSavedId = false;
ChangeAttemptedId = true;
int selectedIndex = VehiclesGridView.SelectedIndex + 1;
getNextRide(selectedIndex); //TODO: FIX
}
ASP.NET Code:
<asp:EntityDataSource ID="VehiclesEDS" runat="server" EnableDelete="True"
EnableFlattening="False" EnableInsert="True" EnableUpdate="True"
EntitySetName="Vehicles" ContextTypeName="RamRideOps.RamRideOpsEntities" >
</asp:EntityDataSource>
<asp:UpdatePanel ID="SelectCarUP" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="VehiclesGridView" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="VehiclesEDS" AutoGenerateColumns="False"
onselectedindexchanged="VehiclesGridView_SelectedIndexChanged"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Vertical" ShowHeaderWhenEmpty="True" AutoPostBack="True">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="GVSelectButton" runat="server" CausesValidation="False"
CommandName="Select" Text="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CarNum" HeaderText="Car" ReadOnly="True"
SortExpression="CarNum" />
<asp:BoundField DataField="CurrPassengers" HeaderText="Passengers"
ReadOnly="True" SortExpression="CurrPassengers" />
<asp:BoundField DataField="MaxPassengers" HeaderText="Capacity" ReadOnly="True"
SortExpression="MaxPassengers" />
<asp:BoundField DataField="Status" HeaderText="Status" ReadOnly="True"
SortExpression="Status" />
<asp:BoundField DataField="StartAdd" HeaderText="Pick-Up Address"
ReadOnly="True" SortExpression="StartAdd" />
<asp:BoundField DataField="EndAdd" HeaderText="Drop-Off Address"
ReadOnly="True" SortExpression="EndAdd" />
<asp:BoundField DataField="AvgRideTime" HeaderText="Avg. Ride Time"
ReadOnly="True" SortExpression="AvgRideTime" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#004812" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#C6940D" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#C6940D" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#9F770B" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Error when changing EventArgs e to GridViewSelectEventArgs:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0123: No overload for 'VehiclesGridView_SelectedIndexChanged' matches delegate 'System.EventHandler'
Source Error:
Line 90: <asp:UpdatePanel ID="SelectCarUP" runat="server" UpdateMode="Conditional">
Line 91: <ContentTemplate>
Line 92: <asp:GridView ID="VehiclesGridView" runat="server" AllowPaging="True"
Line 93: AllowSorting="True" DataSourceID="VehiclesEDS" AutoGenerateColumns="False"
Line 94: onselectedindexchanged="VehiclesGridView_SelectedIndexChanged"
If the parameter that you want to pass to getNextRide is indeed the same as selected index, then i'd make an event handler like this
protected void VehiclesGridView_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
if (ChangeAttemptedId && !IsSavedId)
{
Alert.Show("Dispatch assignment saved... (But you forgot to click Confirm or Cancel!)");
}
IsSavedId = false;
ChangeAttemptedId = true;
int selectedIndex = e.NewSelectedIndex;
getNextRide(selectedIndex); //TODO: FIX
}
also, inside your event handler, you can access the individual members of your grid view like so: VehiclesGridView.Rows[e.NewSelectedIndex].Cells[i] where i is the index of your cell.
Also, can you post the line where you set the datasource of VehiclesGridView, so that i might be able to come up with a cleaner answer