Getting Gidview Hidden field value on button click in ASP.NET - c#

I have a Gridview dtAppend. I want that when I press delete button the selected row record should be deleted from users table.
I first used button field in gridview, as:
<asp:ButtonField Text="Delete" CommandName="DeleteRow" ControlStyle-CssClass="btn btn-danger btn-small" ControlStyle-ForeColor="White" />
<asp:TemplateField visible="false" ItemStyle-Width="0px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField" Visible="false" runat="server" Value='<%# Eval("userId") %>' />
</ItemTemplate>
</asp:TemplateField>
My client says to show JavaScript alert and on clicking yes the record should be deleted. I cannot write onClientClick for button field so I am being forced to use normal Asp button.
on rowCommand of gridview I am getting the hidden field value in this code
if (e.CommandName == "DeleteRow")
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;
}
i am getting thew value in Session but i need above code working Button_ClickEvent like below
protected void deleteButton_Click(object sender, EventArgs e)
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;}
this is where 'e.CommandArgument' gives Error
I cannot use the above code in normal button click as it gives error in e.CommandArgument
Any help?

Simply you can remove visible="false"
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("userId") %>' />

You Better Remove Visible="false" . Because, the value that has to be binded for hidden field will not be binded in to the field if Visible="false" is there. Any how its a hidden field, so make it Visible="true"
EDIT :
How you handled the RowDataBound event of the Grid, are you assigning the CommandArgument for each row, other wise the above concept will not work in Paging. Refer as below
Ex : -
Button btnMail = (Button)e.Row.FindControl("lnkMail");
btnMail.CommandArgument = e.Row.RowIndex.ToString();

I think this would be easy way, instead of using hidden field.
<asp:LinkButton CommandArgument='<%# Eval("userId") %>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" CommandName="DeleteRow" ID="eliminar" runat="server" Text="delete"/>
if (e.CommandName == "DeleteRow")
{
int userId = Int32.Parse(e.CommandArgument.ToString());
}

You can simply send ID as command argument
or
Try the code as below:
var ID = int.Parse(((HiddenField)item.FindControl("HiddenField1")).Value);
sql = "delete from tablename where id=" + ID;

Related

How can i get the textbox value in selected row in gridview

I am working on a project in c# asp.net.
I created a gridview and connected it to a database. My code is like that;
<asp:GridView ID="GridView1" runat="server"
class="table table-bordered table table-hover " AutoGenerateColumns="false" HeaderStyle-Height="40px" OnRowCommand="GridView1_RowCommand1" >
<Columns>
<asp:TemplateField HeaderText="Numune Parçası" >
<ItemTemplate>
<asp:Literal ID="Literal22" runat="server" Text='<%# Eval("Açıklama") %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Analiz">
<ItemTemplate>
<asp:Literal ID="Literal112" runat="server" Text='<%# Eval("Analiz") %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tartım" ItemStyle-Width="10%">
<ItemTemplate>
<asp:TextBox id="txttartim" runat="server" class="form-control" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="10%"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Birim">
<ItemTemplate>
<asp:DropDownList ID="birimlist" class="form-control" runat="server" >
<asp:ListItem>g</asp:ListItem>
<asp:ListItem>mg</asp:ListItem>
<asp:ListItem>ml</asp:ListItem>
<asp:ListItem>cm2</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Kaydet">
<ItemTemplate>
<asp:LinkButton ID="Btn_Indir" runat="server"
class="btn btn-primary btn-sm" Text="Kaydet" CommandName="Open" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#D14124" CssClass="gridheader" ForeColor="White" HorizontalAlign="Left" />
</asp:GridView>
And the code behind is like that
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Open")
{
int RowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
string name = ((TextBox)GridView1.Rows[RowIndex].FindControl("txttartim")).Text;
DropDownList bir = (DropDownList)GridView1.Rows[RowIndex].FindControl("birimlist");
string birim = bir.SelectedItem.Value;
}
}
But my problem is that i can not get the value of textbox and dropdownlist in which selected row.
The strings name and birim is null.
Give this a go:
if (e.CommandName == "Open")
{
GridViewRow selectedRow = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer);
string name = ((TextBox)selectedRow.FindControl("txttartim")).Text;
DropDownList bir = (DropDownList)selectedRow.FindControl("birimlist");
string birim = bir.SelectedItem.Value;
}
Ok, I often just drop in a plane jane asp.net button, and I don't bother with using the GV built in commands (such as command).
However, you have a command, so you can trigger the "row" command as you have.
And the "row command" fires before the selected index fires, and in fact fires before the selected index triggers.
I note that you passing the "ID". It not really necessary, since a GV has what is called DataKeys feature. That feature lets you get the row (database) PK id, but REALLY nice is you don't have to expose, show, or even use a hidden field, or anything else to get that data key. (this is great for several reasons - one being that you don't have to hide or shove away, or even use the command argument to get that database PK row. The other HUGE issue is then your database pk values are NEVER exposed client side - so nice for security).
Ok, So, make sure your row event is being triggered, and you should be able to use this, first the markup for the Linkbutton:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="cmdView" runat="server" Text="View" CommandName="Open" cssclass="btn btn-info" />
</ItemTemplate>
</asp:TemplateField>
Note how I do NOT worry or pass the "ID". As noted, datakeys takes care of this, and in the GV def, we have this:
<asp:GridView ID="GVHotels" runat="server" class="table"
AutoGenerateColumns="false" DataKeyNames="ID"
bla bla bla
So, now our code is this:
protected void GVHotels_RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lBtn = e.CommandSource as LinkButton;
GridViewRow gRow = lBtn.NamingContainer as GridViewRow;
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("Row index click = " + gRow.RowIndex);
Debug.Print("Database PK id = " + PKID);
// get combo box for this row
DropDownList cbo = gRow.FindControl("cboRating") as DropDownList;
Debug.Print("Combo box value = " + cbo.SelectedItem.Value);
Debug.Print("Combo box Text = " + cbo.SelectedItem.Text);
Output:
Row index click = 7
Database PK id = 68
Combo box value = 2
Combo box Text = Good
So, use datakeys - you thus DO NOT have have to put in extra attributes here and there and everywhere to get the PK row value.
In fact, really, using row command is often MORE of a pain, and you can DUMP the command name to trigger that button click. And REALLY nice then is you get a separate nice command "code stub" for each button (or link button) in the GV. (no need to try and shove all that code into the row command, and then a bunch of if/then or "case" statements to run code for a given command.
So, I in fact suggest you use this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="cmdView" runat="server" Text="View"
OnClick="cmdView_Click1" cssclass="btn btn-info" />
</ItemTemplate>
</asp:TemplateField>
So, all we did was add a plane jane good old regular click event. It will not fire row command, and in fact will not trigger "selected index changed" for the GV, but in most cases I don't need them. So, now, if you 2 or 5 buttons, you just think of them as plane jane regular buttons. (just type in onclick in teh markup, and choose "create new event" that intel-sense pops up). So, now our code for the button is seperate, and not part of the row command. Our code thus becomes this:
protected void cmdView_Click1(object sender, EventArgs e)
{
LinkButton lBtn = sender as LinkButton;
GridViewRow gRow = lBtn.NamingContainer as GridViewRow;
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("Row index click = " + gRow.RowIndex);
Debug.Print("Database PK id = " + PKID);
// get combo box for this row
DropDownList cbo = gRow.FindControl("cboRating") as DropDownList;
Debug.Print("Combo box value = " + cbo.SelectedItem.Value);
Debug.Print("Combo box Text = " + cbo.SelectedItem.Text);
}
So, I tend to not bother with row command - better to just have that plane jane click event. Note the use of naming container - but the rest of the code is the same. I would ONLY use "commandName" to trigger the row event, since THEN the gv index changed event fires - and that useful for highlighting the whole row - but if you don't care, then don't even bother with CommandName - just use regular click events, and as noted, this is even better, since then each button gets it 100% own nice little code stub like any other button click tends to have.
So I grabbed a dropdownlist but your code could be say this:
TextBox tBox = gRow.FindControl("txttartim") as TextBox;
debug.Print (tBox.Text);
I solve the problem.
When i write the code in the Page_load section, it works! It is not null anymore.
if (!Page.IsPostBack)
{
load();
..
}

Access HyperLink inside ItemTemplate inside TemplateField ASP.Net WebForms

I have an ASP TemplateField inside a data populated GridView as follows:
<asp:GridView ID="gvReport" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" OnRowDataBound="gvReport_RowDataBound" CssClass="table table-bordered">
<Columns>
<asp:BoundField DataField="Delete" HeaderText="Delete" SortExpression="Delete" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# "Edit?from=Delete&ID=" + Eval("ID") %>' ImageUrl="Assets/SmallDelete.png" SortExpression="PathToFile" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In other words, at the end of each row, there is a delete 'button'. I can tell whether a particular row/record has been deleted by checking the true/false value of the BoundField Delete in my code behind as follows:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell statusCell = e.Row.Cells[0];
if (statusCell.Text == "True")
{
//change ImageUrl of Hyperlink for this row
}
}
Right now, my icon is red for delete, but in the case that a record has already been deleted,
I would like to change the image to a different icon (a blue one).
How can I change this ImageUrl if statusCell evaluates to true?
ok, so we will need two parts here:
We need (want) to persist the data table that drives the grid).
The REASON for this?
We kill about 3 birds with one stone.
We use the data table store/save/know the deleted state
We use that delete information to toggle our image
(and thus don't have to store the state in the grid view).
We ALSO then case use that table state to update the database in ONE shot, and thus don't have to code out a bunch of database operations (delete rows). We just send the table back to the database.
In fact in this example, I can add about 7 lines of code, and if you tab around, edit the data? It ALSO will be sent back to the database. And this means no messy edit templates and all that jazz (which is panful anyway).
Ok, so, here is our grid - just some hotels - and our delete button with image:
markup:
<div style="width:40%;margin-left:20px">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-hover borderhide" >
<Columns>
<asp:TemplateField HeaderText="HotelName" >
<ItemTemplate><asp:TextBox id="HotelName" runat="server" Text='<%# Eval("HotelName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="ORDER BY FirstName" >
<ItemTemplate><asp:TextBox id="FirstName" runat="server" Text='<%# Eval("FirstName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" >
<ItemTemplate><asp:TextBox id="LastName" runat="server" Text='<%# Eval("LastName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" >
<ItemTemplate><asp:TextBox id="City" runat="server" Text='<%# Eval("City") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="cmdDelete" runat="server" Height="20px" Style="margin-left:10px"
ImageUrl="~/Content/cknosel.png"
Width="24px" OnClick="cmdDelete_Click"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdDeleteAll" runat="server" Text="Delete selected" Width="122px"
OnClientClick="return confirm('Delete all selected?')" />
</div>
Ok, and the code to load up the grid - NOTE WE persist the data table!!!!!
Code:
DataTable rstTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
else
rstTable = (DataTable)ViewState["rstTable"];
}
void LoadGrid()
{
// load up our grid
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstTable.Clear();
rstTable.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstTable;
GridView1.DataBind();
}
ViewState["rstTable"] = rstTable;
}
Ok, so far, real plain jane. The result is this:
Ok, so now all we need is to add the delete button click event.
That code looks like this:
protected void cmdDelete_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow rRow = (GridViewRow)btn.Parent.Parent;
DataRow OneRow = rstTable.Rows[rRow.DataItemIndex];
// toggle data
if (OneRow.RowState == DataRowState.Deleted)
{
// undelete
OneRow.RejectChanges();
btn.ImageUrl = "/Content/cknosel.png";
}
else
{
// delete
OneRow.Delete();
btn.ImageUrl = "/Content/ckdelete.png";
}
}
Again, really simple. But NOTE how we use the data table row state (deleted or not).
And this ALSO toggles the image for the delete button.
So, we don't have to care, worry, or store/save the sate in the grid.
So, if I click on a few rows to delete, I now get this:
So far - very little code!!!
Ok, so now the last part. the overall delete selected button. Well, since that is dangerous - note how I tossed in a OnClientClick event to "confirm the delete. if you hit cancel, then of course the server side event does not run.
But, as noted since we persisted the table? Then we can send the table deletes right back to the server without a loop. The delete code thus looks like this:
protected void cmdDeleteAll_Click(object sender, EventArgs e)
{
// send updates (deletes) back to database.
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels WHERE ID = 0",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daUpdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daUpdateBuild = new SqlCommandBuilder(daUpdate);
daUpdate.Update(rstTable);
}
LoadGrid(); // refesh display
}
So, note how easy it is to update (delete) from the database. If you look close, I used text boxes for that grid - not labels. The reason of course is that if the user tabs around in the grid (and edits - very much like excel), then I can with a few extra lines of code send those changes back to the database. In fact the above delete button code will be 100% identical here (it will send table changes back with the above code. So, if we add rows, edit rows then the above is NOT really a delete command, but is in fact our save edits/deletes/adds command!

Nesting Gridview inside Formview breaks insert codebehind context

I have a couple of GridViews in my FormView page and I am wanting to make an Insert row in the FooterRow of the Gridviews. Layout and everything is fine. However, as I'm building the codebehind for the Insert command, I'm running into a context problem. If I move the GridView outside of the FormView markup, the context errors clear up immediately.
GridView Markup
<asp:GridView ID="gvBFMats" runat="server" ShowFooter="True" AutoGenerateColumns="False" DataKeyNames="MaterialID" DataSourceID="BFMatsSQL" OnRowCommand="gvBFMats_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Commands" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="ButtonUpdate" 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="ButtonEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="ButtonDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="ButtonAdd" runat="server" CommandName="Insert" Text="Add to Table" />
</FooterTemplate>
...
Insert Command Codebehind
protected void gvBFMats_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert" && Page.IsValid)
{
BFMatsSQL.Insert();
}
}
protected void BFMatsSQL_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
{
DropDownList ddlNewMfr =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewMfr");
DropDownList ddlNewThickness =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewThickness");
DropDownList ddlNewCore =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewCore");
DropDownList ddlNewSize =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewSize");
TextBox txtNewColor =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewColor");
TextBox txtNewQty =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewQty");
DropDownList ddlNewFinish =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewFinish");
TextBox txtNewExtra =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewExtra");
// Set the SQLDataSource's InsertParameters values
e.InputParameters["MatManufacturerID"] =
Convert.ToInt32(ddlNewMfr.SelectedValue);
e.InputParameters["MatThicknessID"] =
Convert.ToInt32(ddlNewThickness.SelectedValue);
e.InputParameters["MatCoreID"] =
Convert.ToInt32(ddlNewCore.SelectedValue);
e.InputParameters["MatSizeID"] =
Convert.ToInt32(ddlNewSize.SelectedValue);
e.InputParameters["MatFinishPrePostID"] =
Convert.ToInt32(ddlNewFinish.SelectedValue);
string strNewColor = null;
if (!string.IsNullOrEmpty(txtNewColor.Text))
strNewColor = txtNewColor.Text;
e.InputParameters["MatFinishColor"] = strNewColor;
int? intNewQty = null;
if (!string.IsNullOrEmpty(txtNewQty.Text))
intNewQty = Convert.ToInt32(txtNewQty.Text);
e.InputParameters["MatQty"] = intNewQty;
string strNewExtra = null;
if (!string.IsNullOrEmpty(txtNewExtra.Text))
strNewExtra = txtNewExtra.Text;
e.InputParameters["MatNumExtraSheets"] = strNewExtra;
}
Specifically, I get the red squiggly under the gvBFMats in the (Control)gvBFMats.FooterRow.FindControl("Control ID"); that says "The name 'gvBFMats' does not exist in the current context." I'm only guessing that it doesn't like the call to the GridView when it's nested inside a FormView template. Is there a way to pass this context along programatically?
You're right about it not recognizing the name gvBFMats because it's embedded in a template. Only "top-level", non-embedded controls will be treated in Code Behind as if they had been explicitly declared. Controls declared in a template will not. The compiler doesn't recognize those names.
There's a reason for this. Imagine you have a control called TextBox1 in one of the ItemTemplates for a repeating control. You bind it. Your page's control tree now has dozens of controls with the ID TextBox1. If you want to refer to TextBox1, how does it know which one you mean?
So. What can you do in your situation? Well, BFMatsSQL_Inserting and gvBFMats_RowCommand are both event handlers, so you can't change their signatures.
But, you can make use of them belonging to the same class, and use a module-level variable to hold the reference to gvBFMats. Like this:
private GridView gvBFMats;
protected void gvBFMats_RowCommand(object sender, GridViewCommandEventArgs e)
{
gvBFMats = [your form view].Row.FindControl("gvBFMats") as GridView;
if (e.CommandName == "Insert" && Page.IsValid)
{
BFMatsSQL.Insert();
}
}
Now, BFMatsSQL_Inserting will be able to refer to gvBFMats, and it should have a value.

How can I pass Hidden Field value with CommandArgument of LinkButton?

I have one Repeater with multiple rows.each row has one LinkButton and one HiddenField.
HiddenField value is bind at time of Repeater's Event OnItemDataBound.
My Question is that How can I pass this HiddenField Field Value with CommandArgument of this LinkButton?
Following is my source code.
<asp:Repeater ID="rptServiceRequestList" runat="server" OnItemCommand="rptServiceRequestList_ItemCommand" OnItemDataBound="rptServiceRequestList_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="btnCustomerDeposit" runat="server" Text="Pay Deposit" CommandName="DepositFees" CommandArgument='<%# Eval("ServiceRequestId") %>'>
</asp:LinkButton>
<asp:HiddenField ID="hidAmount" runat="server" />
</asp:Repeater>
Please Help me. thank you to all in advance.
Yes you can set multiple command argument or the another way is you can use FindControl("hidAmount") method of repeater .
You can use below code.
HiddenField hdnAmount = (HiddenField)rptServiceRequestList.FindControl("hidAmount");
int amnt = Convert.ToInt32(hdnAmount.Value);
You can set multiple command argument(to send hidamount along with command Argument) as:
<asp:LinkButton ID="btnCustomerDeposit" runat="server" Text="Pay Deposit" CommandName="DepositFees" CommandArgument='<%#Eval("ServiceRequestId") + "|" +Eval("HidAmount")%>'
</asp:LinkButton>
And on ItemCommand:
protected void rptServiceRequestList_ItemDataBound(Object Sender, RepeaterCommandEventArgs e)
{
string[] arg = new string[2];
arg = e.CommandArgument.ToString().Split('|'); // Split Here to seprate CommandName And Hidden Value
string YourcommandName = arg[0]; // Your Command Name
string YourHiddenValue = arg[1]; // Your Hidden Field Value
}

Get the Current Selected Row of GridView on a button Click

I want to fetch the DataKey of the Selected Row of GridView on button click.
I would Personal do it in a Template Field Like so:
<asp:TemplateField>
<ItemTemplate>
//EDIT: after a comment it is suggested that you pass the RowIndex as the command argument which would provide access to the entire row
<asp:LinkButton ID="btnCopy" runat="server"CausesValidation="False"CommandName="MyCommandButton"CommandArgument='<%# Eval("MyDataKeyOrWhateverIWanteverIWantFromTheBindingSource")%>'>
</ItemTemplate>
</asp:TemplateField>
CodeBehind
protect void MyCommandButton(Object sender,CommandArgument e)
{
int DataKeyOrPK=int32.Parse(e.CommandArgument.ToString());
}
You other option would be:
<asp:gridview id="myGrid" runat="server"
width=100% datakeynames="Myid"
autogeneratecolumns=false
onSelectedIndexChanged="MyEvent">
<asp:templatefield headertext="Choose your dream home">
<itemtemplate>
<asp:linkbutton runat="server" commandname="select" text='<%# Eval ( "Whatever" ) %>' />
</itemtemplate>
</asp:templatefield>
Note the commandname="select" above.
Data-bound controls recognize certain command names and automatically raise and handle the appropriate events for the control. The following command names are recognized:
Cancel, Delete, Edit, Insert, New, Page, Select, Sort and Update. Reference
Codebehind
private void MyEvent(Object sender, EventArgs e)
{
string id = myGrid.SelectedDataKey.Value.ToString();
}
Use the SelectedDataKey property of the GridView:
DataKey currentKey = myGridView.SelectedDataKey;

Categories