Access gridview row's data from LinkButton inside that row - c#

Each row of the GridView is populated from a SQL DB.
Each row has a LinkButton that brings up a popup.
In the code behind I want to have access to the DataField="RCID"
I guess I'd like to attach the RCID field to the Upload link so when it's clicked I have access to the RCID within the function that handles the onclick.
How do I get this rows RCID?
<asp:GridView ID="GridView1" runat="server"
OnPageIndexChanging="GridView1_PageIndexChanging"
GridLines="Horizontal" AllowPaging="true" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="RCID" DataField="RCID" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="RC Type" DataField="RCType"></asp:BoundField>
<asp:BoundField HeaderText="Channel" DataField="Channel"></asp:BoundField>
<asp:BoundField HeaderText="Total" DataField="Total"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 30 Days" DataField="ExpiredIn30Days"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 60 Days" DataField="ExpiredIn60Days"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 90 Days" DataField="ExpiredIn90Days"></asp:BoundField>
<asp:BoundField HeaderText="Last Updated" DataField="LastUpdated"></asp:BoundField>
<asp:TemplateField HeaderText="Management">
<ItemTemplate>
<asp:LinkButton runat="server" ID="Upload" Text="Upload" CommandName="Upload" ></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Details" Text="Details" CommandName="Details"></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Files" Text="Files" CommandName="Files"></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Edit" Text="Edit" CommandName="Edit"></asp:LinkButton> |
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Possible solution would be as follows:
Add RowCreated and RowCommand events for GridView
In RowCreated event, I have set “Visible” property to “false” for first column for both header and data row.
In RowCommand event, CommandName is checked first and then index for select command is retrieved. I have retrieved the row for that index and then retrieved the text in the specified row cell.
check this example:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Visible = false;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label1.Text = (row.Cells[0].Text);
}
}
Second approach:
Assign command argument to your hidden field value. This will reduce another efforts. check this way:
<asp:TemplateField HeaderText="Action3" Visible="false">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="lnkretqty" runat="server" Text="Return Qty" CommandName="RETQTY" ToolTip="Click here to Add Return Qty Entry"
CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind code
protected void gvsearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "SRCSELREC")
{
Int32 rowind = Convert.ToInt32(e.CommandArgument.ToString());
string val = ((Label)gvgpitemdtl.Rows[rowind].FindControl("d")).Text.ToString();
}
}
catch (Exception ex)
{
General.MessageBox(this.Page, "Error at Gridview Row Command : " + ex.Message.ToString());
return;
}
}
References:
Way of getting Hidden column value in GridView
How to Get Hidden Column values in GridView
To Find Control in GridView on RowCommand event in asp.net
How to hide GridView column and retrieve value from hidden column cell in ASP.NET

Add CommandArgument='<%# Eval("RCID") %>' in the linkbutton's markup:
<asp:LinkButton runat="server" ID="Upload" Text="Upload" CommandName="Upload" CommandArgument='<%# Eval("RCID") %>'/>
Now, in the code behind of the handler, just read the CommandArgumentproperty of the passed GridViewCommandEventArgs parameter:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Upload")
{
var valueOfRCID = e.CommandArgument;
}
}

mshsayem may be right but note you can also just grab the value from within the click event as follows
<asp:LinkButton runat="server" ID="Upload" Text="Upload" OnClick="Upload_Click" CommandArgument='<%# Eval("RCID") %>'/>
protected void Upload_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string RCID = btn.CommandArgument;
}

Related

Gridview delete row from database

I want to to delete record(s) from table through C# gridview. The problem is that the rows are only getting deleted from gridview and not from table. I want to remove them from DB as well. here is my code.
private void Delete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
string a = (string )this.dataGridView1.CurrentCell.Value;
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
DeleteRecord(a);
}
Now I want the definition of function DeleteRecord(a) its a humble request to give the code for this function which will obviously have the sql query so that i may delete the rows from table by getting the id of selected row.
It is rather impossible to tell the exact answer.
Multiple ways:Let me show one.
1)Aspx page
<asp:GridView DataKeyNames="CategoryID" ID="GridView1"
runat="server" AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1"
CommandArgument='<%# Eval("CategoryID") %>'
CommandName="Delete" runat="server">
Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
2)Add rowdatabound event.
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record " +
DataBinder.Eval(e.Row.DataItem, "CategoryID") + "')");
}
}
3)And finally RowCommand:
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
// get the categoryID of the clicked row
int categoryID = Convert.ToInt32(e.CommandArgument);
// Delete the record
DeleteRecordByID(categoryID);
// Implement this on your own :)
}
}

How to get value of a gridview cell in this scenario

I have a link button inside a gridView as below :
<asp:TemplateField HeaderText="Analyze">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Analyze" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
I have the LinkButton1_Click function as below :
protected void LinkButton1_Click(object sender, EventArgs e)
{
testtb.Text = name;
Console.WriteLine(name);
}
This variable "name" is the first column of the GridView.I am obtaining the value for "name" as below:
protected void UnanalysedGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView d = (DataRowView)e.Row.DataItem;
name = d["resultId"].ToString();
}
}
I want that on click of the link button the value of first column in that row of gridview becomes the text for the textbox testtb.
Somehow,the value for name remains null.
EDIT
I found out that probably RowDataBound isn't the correct event for my requirements because I need the value for each row.
So I removed the RowDataBound function.
I guess I have to handle this inside LinkButton1_Click itself.
I added this line to the function :
name = UnanalysedGV.SelectedRow.Cells[1].Text;
Still doesn't work.
Does anyone have any idea ?
You can do it using two approaches as mentioned below.
Handle click event of linkbutton through event bubbling code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging" OnRowCommand="grdCustomPagging_RowCommand">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("DealId") %>'
CommandName="VIEW">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCustomPagging_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "VIEW")
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string dealId = lnkView.CommandArgument;
}
}
Handle click event of linkbutton directly click event code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" OnClick="lnkView_Click">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void lnkView_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string rowNumber = grdrow.Cells[0].Text;
string dealId = grdrow.Cells[1].Text;
string dealTitle = grdrow.Cells[2].Text;
}
Hope this helps.

ASP.NET Gridview ButtonField onclick fires containing row's onclick event

I have a gridview row that when clicked has to do postback A and a buttonfield in that row that when clicked has to do postback B. The problem is that when i click on the buttonfield, both event1 and event2 gets fired. Below is the code.
protected void gdv_RowCommand(object sender, GridViewCommandEventArgs e)
{
string arg = Convert.ToString(((System.Web.UI.WebControls.CommandEventArgs)(e)).CommandArgument);
if (e.CommandName == "Command1")
{
doEvent1(arg);
}
else if (e.CommandName == "Command2")
{
doEvent2(arg);
}
}
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton b1 = (LinkButton)e.Row.Cells[0].Controls[0];
matchesButton.CommandArgument = arg1;
LinkButton rowLink = (LinkButton)e.Row.Cells[1].Controls[1];
rowLink.CommandArgument = arg2;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(rowLink, "");
}
}
And this is the asp code for the gridview
<Columns>
<asp:ButtonField DataTextField="f1" HeaderText="H1" CommandName="Command1" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btn1" runat="server" Text="" CommandName="Command2" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
try to use this
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Command2")
{
// Your Code here
}
}
to find control in grid view use this code
LinkButton lnkbtn= (LinkButton)e.Row.FindControl("btn1");
Try adding both the button with in same <asp:TemplateField> if you don't want separate headers
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="button" runat="server" CommandName="Command1" />
<asp:LinkButton ID="btn1" runat="server" CommandName="Command2" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
if you want separate headers make two separate <asp:TemplateField> and then add buttons in them.

How to get row data by clicking a button in a row in an ASP.NET gridview

I have a GridView in a ASP.NET web application, in which I have added two buttons in each row:
<ItemTemplate>
<asp:Button ID="btnEdit" Text="Edit" runat="server" />
<asp:Button ID="btnDelete" Text="Delete" runat="server"/>
</ItemTemplate>
Now how I can get the row data from gridview simply by clicking an edit button in a row?
You can also use button click event like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
OR
You can do like this to get data:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
and Button in gridview should have command like this and handle rowcommand event:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
</columns>
</asp:gridview>
Check full example on MSDN
Place the commandName in .aspx page
<asp:Button ID="btnDelete" Text="Delete" runat="server" CssClass="CoolButtons" CommandName="DeleteData"/>
Subscribe the rowCommand event for the grid and you can try like this,
protected void grdBillingdata_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteData")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
HiddenField hdnDataId = (HiddenField)row.FindControl("hdnDataId");
}
}
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void LnKB_Click(object sender, System.EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
int x = clickedRow.RowIndex;
int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
lbl.Text = yourgridviewname.Rows[x].Cells[2].Text;
}
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" CssClass="CoolButtons"/>
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btnEdit = (Button)sender;
GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
//Get the gridview Row Details
}
And Same As for Delete button
protected void btnS10_click(object sender, EventArgs e)
{
foreach (GridViewRow row in Grd.Rows)
{
CheckBox chk_Single = (CheckBox)row.FindControl("ChkSendOne");
if (row.RowType == DataControlRowType.DataRow)
{
string id = (row.Cells[0].FindControl("lblSNo") as Label).Text;
if (Convert.ToInt32(id) <= 10)
{
chk_Single.Checked = true;
if (chk_Single.Checked == true)
{
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
}
}
}

Accessing GridView data from a templatefield

<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1"
SortExpression="Field1" />
<asp:BoundField DataField="Field2" HeaderText="Field2"
SortExpression="Field2" />
<asp:TemplateField HeaderText="TemplateField1">
<ItemTemplate>
<asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
<asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnComplete_Click(object sender, EventArgs e)
{
String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
//I want to be able to access the row data do some computation and then be able to insert it into the database
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition.
}
Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.
You can do it like this:
protected void btnComplete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
//Alternatively you could use NamingContainer
//GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
Label lblComments = (Label)gvRow.FindControl("lblComments");
// lblComments.Text ...whatever you wanted to do
}
here is how you can access to the gridview row:
protected void btnComplete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvGrid.Rows)
{
Label lblComments = row.FindControl("lblComments") as Label;
....//you can do rest of the templatefiled....
}
}

Categories

Resources