How to call specific method when user click on row in GridView - asp.net

I add below line to each row and when i click on row in GridView i can select it(means event GridView_SelectedIndexChanged hire) how can i change it that when i click on row specific method call
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);

in view:
<script type="text/javascript" language="javascript">
function show(id) {
alert(id);
// Do something as your need
}
</script>
<asp:GridView runat="server" ID="GridView1" DataKeyNames="DepartmentID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small"
OnRowDataBound="GridView1_RowDataBound" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID"
InsertVisible="False" ReadOnly="True" SortExpression="DepartmentID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Budget" HeaderText="Budget"
SortExpression="Budget" />
<asp:BoundField DataField="StartDate" HeaderText="StartDate"
SortExpression="StartDate" />
<asp:BoundField DataField="Administrator" HeaderText="Administrator"
SortExpression="Administrator" />
</Columns>
</asp:GridView>
inCodeBehind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
e.Row.Attributes["onclick"] = "show(" + e.Row.RowIndex.ToString() + ");";
}
}

Use GridView.RowCommand Event: The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="YourCommandName")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GridView1.Rows[index];
//Your Code
}
}

<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//add css to GridViewrow based on rowState
e.Row.CssClass = e.Row.RowState.ToString();
//Add onclick attribute to select row.
e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
}
}

Related

How do i know which Buttons are triggered to perform specific task in Gridview

I have 2 buttons, one is called "Accept", which is used for updating of database while another is called "View", which is used for Redirecting. However, in GridView's SelectedIndexChanged, i wasnt able to Validate which buttons were click
so I have tried Using RowCommand for the "View" button and SelectedIndexChanged for "Accept" button. But RowCommand is triggering the "Accept" button in the SelectedIndexChanged event handler.
<asp:GridView ID="QgridView" AutoGenerateColumns="False"
CssClass="table table-bordered" AllowPaging="True" PageSize="6"
BackColor="White" BorderColor="Black" BorderStyle="Solid"
ForeColor="Black" GridLines="None" runat="server"
OnRowCommand="QgridView_RowCommand"
OnSelectedIndexChanged="QgridView_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<span>
<%#Container.DataItemIndex + 1%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="Image" DataImageUrlField="coverimg" >
<ControlStyle CssClass="coverimage"/>
<ItemStyle HorizontalAlign="Center" />
</asp:ImageField>
<asp:BoundField HeaderText="Buyer" DataField="buyer" />
<asp:BoundField HeaderText="Item" DataField="item" />
<asp:BoundField HeaderText="Price offered" DataField="price" />
<asp:buttonfield buttontype="Button"
commandname="Accept"
text="Accept"/>
<asp:BoundField DataField="quoteid" HeaderText="quoteid" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="id" HeaderText="id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="rtype" HeaderText="rtype" ItemStyle-
CssClass="hiddencol" HeaderStyle- CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="seller" HeaderText="seller" ItemStyle-
CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:buttonfield buttontype="Button"
commandname="View"
text="View"/>
</Columns>
</asp:GridView>
// Behind COde page
protected void QgridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = QgridView.SelectedRow;
string seller = row.Cells[10].Text;
string item = row.Cells[4].Text;
string type = row.Cells[9].Text;
int id = Convert.ToInt32(row.Cells[8].Text);
int quoteid = Convert.ToInt32(row.Cells[7].Text);
productDAO productdao = new productDAO();
productdao.GridPush(quoteid, id)
}
protected void QgridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("ListingItems.aspx");
}
}
I want the "Accept" BUtton to perform the updating of database while the "View button to perform Response.Redirect. However, RowCommand does not fire and instead, it triggers the "Accept" button in SelectedIndexChanged. May i know how can perform the different task for each button?
[Gettting row data from GridView]
protected void QgridView_RowCommand(object sender,
GridViewCommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("onrowcommand");
if (e.CommandName == "View")
{
System.Diagnostics.Debug.WriteLine("ButtonView is clicked");
Response.Redirect("ListingItems.aspx");
}
else if (e.CommandName == "Accept")
{
System.Diagnostics.Debug.WriteLine("buttonAccept is clicked");
productDAO productdao = new productDAO();
//GridViewRow row = QgridView.SelectedRow;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = QgridView.Rows[index];
string id = row.Cells[8].Text; //Returns me nothing
}
else
{
System.Diagnostics.Debug.WriteLine("no command name");
}
}
I think you are no need to check the rowcommand or onselected Index change event you can directly set button on click event. if you are using the inside your Gridview, then you should be able to register an event in your button code as:
<asp:Button runat="server" OnClick="YourclickEvent" />
For more details on event you should read this: https://www.codeproject.com/Articles/50540/GridView-Event-Handling
One Addition: if using row command then identify each button with command name and you can perform your task easily.
According to your code SelectedIndexChanged should be never fired (no select command).
RowCommand handler always fire first (before more specific handlers).
Look at sample working code.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID"
DataSourceID="sqlCategory"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:ButtonField ButtonType="Button" CommandName="Accept" HeaderText="Accept" ShowHeader="True" Text="Accept" />
<asp:ButtonField ButtonType="Button" CommandName="View" HeaderText="View" ShowHeader="True" Text="View" />
<%-- Use HyperLinkField instead of ButtonField --%>
<asp:HyperLinkField DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="category.aspx?categoryid={0}" DataTextField="CategoryName" DataTextFormatString="View {0}" HeaderText="Direct View" />
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
<%-- Data from NorthWind learning DB --%>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
UpdateCommand="update categories set categoryName=#CategoryName where CategoryID=#CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
<asp:Parameter Name="CategoryName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Trace.Write("GridView1_SelectedIndexChanged");// fired by "select" command after RowCommand finished
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Trace.Write("GridView1_RowCommand");
//
if (e.CommandName == "Accept")
{
var categoryId = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;//e.CommandArgument is display index
Trace.Write(e.CommandName + ": " + e.CommandArgument + " : " + categoryId.ToString());
}
else if (e.CommandName == "View")
{
Trace.Write("View " + e.CommandArgument);
}
}

Dynamic button in gridview ASP.NET c#

i have a grid view in Asp.net. i want to generate button for specific rows.
Like i have a column named as "Status". If status is "Accept" a button should be generated in that particular row.
column
You can use a TemplateField in ASP.NET GridView and conditionally set the Button visibility, like shown below:
<asp:GridView runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Accept"
Visible='<%# Eval("Status")=="Accept" %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Hope this will help.
first add template field button like this
<asp:TemplateField HeaderText="status" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btn" runat="server" CausesValidation="false"
CommandName="Select" Text="button" />
</ItemTemplate>
</asp:TemplateField>
and codebehind
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = (Button)e.Row.FindControl("btn");
if (e.Row.Cells[1].Text == "Accept")//replace 1 by your column(status) index in gridview
{
btn.Visible = true;
}
else
{
btn.Visible = false;
}
}
}
and to add code to this button so add it on
protected void grid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//code
}

How to make 1row to 2rows GridView in asp.net?

I have GridView with 5 items like this.
I want to make this GridView as below big red square. How can I make 2rows in one GridView?
ASP Code :
<asp:GridView ID="GridView" runat="server" DataSourceID="GridView1"
OnRowCreated="GridView1_RowCreated" AutoGenerateColumns="false" EmptyDataText="표시할 내용없음">
<Columns>
<asp:BoundField DataField="Seq"/>
<asp:BoundField DataField="Title" />
<asp:BoundField DataField="UUSER" />
<asp:BoundField DataField="NoticeDate" />
<asp:BoundField DataField="SCnt" />
</Columns>
</asp:GridView>
C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].Visible = false;
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].Visible = false;
//e.Row.Cells[1].Attributes.Add("colspan", "2");
}

how to dynamically add button in gridview cell

gridview cannot add an 'approve' button in gridview,can someone can help me thanks
http://i260.photobucket.com/albums/ii8/elvenchan2/rowAdd.png
behind code
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
dr.Cells[10].Controls.Add((Control)btn);
}
}
}
}
u must add a 10th cell at first
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
//Declare the bound field and allocate memory for the bound field.
ButtonField btnRent = new ButtonField();
//Initalize the DataField value.
btn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
btn.CommandName = "Button";
btn.ButtonType = ButtonType.Button;
btn.Text = "Rent";
btn.Visible = true;
//Add the newly created bound field to the GridView.
GridView2.Columns.Add(btn);
}
}
}
}
Since there is no criteria for creating the button, why not just make a TemplateField in your GridView markup and wire up a click handler or CommandName for the button, like this:
<asp:GridView id="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="ButtonApprove" runat="server"
CommandName="approve" Text="Approve" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle each individual approve button click, like this:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "approve")
{
// Do approval logic here
}
}
You can try it:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
PlaceHolder ph = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
Button b1 = new Button();
b1.ID = "Approve";
b1.Text = "Approve"
ph.Controls.Add(b1);
}
}
Of course, you should add a placeholder in the html template. like
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Button add here..
</asp:PlaceHolder>
</ItemTemplate>
Design
<asp:GridView ID="viewThemeTypeAssociationsGridView" runat="server" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2"
OnRowDataBound="viewThemeTypeAssociationsGridView_RowDataBound"
DataSourceID="Sql_New" >
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"
InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:TemplateField HeaderText ="New Column" >
<ItemTemplate >
<asp:Button ID="btnnew" runat ="server" Visible ="false" ></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="Sql_New" runat="server"
ConnectionString="<%$ ConnectionStrings:EmployeeConnectionString %>"
SelectCommand="SELECT * FROM [tblnew]"></asp:SqlDataSource>
Code
protected void viewThemeTypeAssociationsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[2].Text == " ")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnnew = (Button)e.Row.FindControl("btnnew");
btnnew.Visible = true;
}
}
}

How can i call a code behind function when user clicks a gridview row?

I have a gridview in an aspx page with c# code behind.
Is there a way how i can run a code behind function when the user clicks anywhere on a row? For now, i use the select button. But then the user has to click on that button. And i want to user to be able to click anywhere on a row to show it's details in another gridview that is located next to the main gridview.
Some ideas here on how to do this?
Thanks!
try this
<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = Enumerable.Range(1, 10).Select(a => new
{
ID = a,
FirstName = String.Format("First {0}", a),
LastName = String.Format("Last{0}", a)
});
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//Bind other grid
Response.Write(GridView1.SelectedIndex+1);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//add css to GridViewrow based on rowState
e.Row.CssClass = e.Row.RowState.ToString();
//Add onclick attribute to select row.
e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
}
}

Resources