GridView identify clicked row values? - c#

I have this gridview:
<div class="content">
<asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="DocumentGrid_RowCommand" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download"/>
</Columns>
</asp:GridView>
</div>
As you can see, DocumentGrid_RowCommand is called when the "Download" button is pressed, How can I find out what the values are of the row that was clicked?

If more than one button fields are there in GridView, set CommandName attribute. That way we can determine which button is pressed in RowCommand event. So always set commandName attribute.
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download" CommandName="cmd"/>
</Columns>
In RowCommand event handler, GridViewCommandEventArgs.CommandArgument property returns index of row on which button is pressed.
protected void DocumentGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
int index = int.Parse(e.CommandArgument.ToString());
GridViewRow row = DocumentGrid.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
Response.Write(row.Cells[0].Text);
}
}
}

If you set the markup like this,
<Columns>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:Button ID="btnDownload" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>'
runat="server" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
on the code-behind you can check the CommandArgument like this:
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
}

Related

Image button on gridview not triggering asp.net

so i have a gridview with an imagebutton, thing is that it never triggers. I dont know why. here is the code.
<asp:GridView ID="GridView1" runat="server" Width="233px"
OnCommand="GridView1_RowCommand" onrowcommand="GridView1_RowCommand"
DataKeyNames="Nombre">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="12%" ItemStyle-
HorizontalAlign="Center" >
<ItemTemplate>
<asp:ImageButton ID="lnkEditar" runat="server" CommandName="Edit"
ImageUrl="Imagenes/edit.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
Label1.Text = GridView1.Rows[index].Cells[2].ToString();
}
}
I debugged it and it never triggers the RowCommand event. Any help is thanked!
Try to change as follow OnRowCommand
OnRowCommand="GridView1_RowCommand"

Can't bind checkboxes in Gridview

I have a GridView that displays a list and the user can select a checkbox for each item.
So for example I check the second row. I can see in the database that the check value next to this description has updated to 1:
But when I go back into the GridView, all the checkboxes are blank again.
Code for GridView:
<asp:GridView style="width:75%"
ID="gvCVRTDetails"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvCVRTDetails_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
AlternatingRowStyle-BackColor="#EEEEEE">
<HeaderStyle CssClass="tblResultsHeader" />
<Columns>
<asp:BoundField DataField="ChecklistID" HeaderText="ID" ></asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Checklist Items"></asp:BoundField>
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void gvCVRTDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lookupCVRT work = (lookupCVRT)e.Row.DataItem;
GridView gv = sender as GridView;
e.Row.Attributes.Add("ID", "gvCVRTDetails_" + work.ID);
e.Row.Cells[0].Attributes.Add("onclick", "event.stopPropagation();");
CheckBox chkChecked = e.Row.FindControl("chkChecked") as CheckBox;
if(work.Checked)
{
chkChecked.Checked = true;
}
}
}
I tried setting chkChecked.Checked = true; if there is a value for the Checked field in the database but that didn't work. How do I get the checkboxes to show as ticked if the value in the database is equal to 1?
Binding the Grid:
protected void gridviewParent_SelectedIndexChanged(object sender, EventArgs e)
{
List<lookupCVRT> workDetails = lookupCVRT.GetChecklistItemsByChecklistID(Company.Current.CompanyID, ParentID.ToString(), gvCVRT.SelectedDataKey.Value.ToString());
gvCVRTDetails.DataSource = workDetails;
gvCVRTDetails.DataBind();
FireJavascriptCallback("setArgAndPostBack ();");
}
You should bind the checkbox to the property that you read from db, something like:
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" Checked='<%# Bind("YourCheckPropertyFromModel") %>'runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>

Asp GridView select a row then fire event

Here is the scenario ..
I have a GridView with columns ID, Name, and Type. Name is click enabled and will redirect to other page. The entire row can be selected, and using jQuery I changed its background so it will be recognized as selected row.
The reason it must be selected is because a link, for example Delete is present at the page. When Delete is clicked, it should delete the selected row but when there is no selected row, it should do nothing.
Here is my code:
<asp:LinkButton ID="btnDelete" runat="server">Delete</asp:LinkButton>
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound" OnRowCommand="gridView_Command" AutoGenerateColumns="false" >
<columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</columns>
</asp:GridView>
public void gridView_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "NameButton")
{
var id = e.CommandArgument;
// redirect to edit page //
}
}
I am using jQuery to indicate that a row is selected.
I already have the code for the Delete event method but my problem is how can I tell the compiler that a row is currently selected upon clicked of Delete?
I am thinking of using a hidden field, and on jQuery, I will set the value of the hidden field to the ID of the row that is selected. However, I still don't have the idea on how to do it.
It is pretty straight. You can store the SelectedIndex in a hidden field and find the GridViewRow by the index.
Add a hidden field in the markup and also attach an event method to the Link button:
<asp:LinkButton ID="btnDelete" OnClick="btnDelete_Click" runat="server">Delete</asp:LinkButton>
<asp:HiddenField ID="hdnIndex" runat="server" />
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound"
OnRowCommand="gridView_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</Columns>
</asp:GridView>
In the GridView RowDataBound add an attribute to execute javascript to save index in hidden field:
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript: getElementById('" + hdnIndex.ClientID + "').value='" + e.Row.RowIndex + "';");
}
}
And LinkButton's click event do like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
int index = 0;
int id = 0;
if (int.TryParse(hdnIndex.Value, out index))
{
GridViewRow gvr = gridView.Rows[index];
if (gvr != null && int.TryParse(gvr.Cells[0].Text, out id) )
{
// id is available here
// do wahtever you want with the id
// even you can delete the record from db by id
}
}
}
I guess command-argument is what you are searching for...Check this link
You just need to pass the Id using command argument from front-end to the code file and from there you can delete it easily.

How to populate multiple textboxes from a row in gridview that uses a link button

I'm trying to populate multiple text boxes with data from a gridview when I click the link button (which is in fact the name of one of the fields in each row) but it isn't going through. I'm new to this - literally my first time. Any help would be most appreciated.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
AccountNumber.Text = selectedRow.Cells[1].Text;
Name.Text = selectedRow.Cells[1].Text;
Address1.Text = selectedRow.Cells[1].Text;
Address2.Text = selectedRow.Cells[2].Text;
Address3.Text = selectedRow.Cells[3].Text;
PhoneNumber.Text = selectedRow.Cells[4].Text;
FaxNumber.Text= selectedRow.Cells[5].Text;
CurrencyID.Text = selectedRow.Cells[6].Text;
}
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="Agent_Account_No"
DataSourceID="SqlDataSource1"
AlternatingRowStyle-BackColor ="Lavender"
HeaderStyle-BackColor="#9966FF"
AllowSorting="True" HeaderStyle-BorderColor="Black"
HorizontalAlign="Center"
RowStyle-BorderColor="Black"
EmptyDataText="There are no data records to display."
onrowcommand ="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCFFCC" />
<Columns>
<asp:BoundField datafield="Agent_Account_No" HeaderText="Account No"
ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="50"
SortExpression="Agent_Account_No"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"
Width="50px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I got it to work this way - using help from this site:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = GridView1.DataKeys[row.RowIndex]["Agent_Account_No"].ToString();
......
}
I don't know if this declaration is right, but it works. However now that it works I see a problem that I didn't see before - see my profile and thanks a lot!
I would highly recommend using TemplateFields for all of your columns, like this:
Markup:
<Columns>
<asp:TemplateField HeaderText="Account No" SortExpression="Agent_Account_No">
<ItemTemplate>
<asp:Label ID="LabelAccountNumber" runat="server"
Text='<%# Eval("Agent_Account_No") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now in the RowCommand method, you can use the FindControl() method of the grid view row to get to the text you are interested in, like this:
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// Find the account number label to get the text value for the text box
Label theAccountNumberLabel = selectedRow.FindControl("LabelAccountNumber") as Label;
// Make sure we found the label before we try to use it
if(theAccountNumberLabel != null)
{
AccountNumber.Text = theAccountNumberLabel.Text;
}
// Follow the same pattern for the other labels to get other text values
}
}

DataKeyValues are null in gridview

Here is my gridview and the event that fires when a user clicks on the edit button within the row. for some reason my datakey value is crashing the program saying it is null. im not sure why. the DataKeyNames in the gridview is exactly what I want it to be, formID. this is correct because the last column in the gridview, as you can see, shows me the formID and it displays just fine. so i have no idea where i am going wrong.
<asp:GridView ID="gvHistory" runat="server" DataSourceID="ObjectDataSource"
AutoGenerateColumns="False" CellPadding="10" CellSpacing="5"
CssClass="userHistory" DataKeyNames="formID">
<Columns>
<asp:BoundField DataField="clientName" HeaderText="User" />
<asp:BoundField DataField="formName" HeaderText="Form" />
<asp:BoundField DataField="dateCreated" HeaderText="Date Created" />
<asp:BoundField DataField="dateRevised" HeaderText="Last Revision Date" />
<asp:BoundField DataField="dateSubmitted" HeaderText="Date Submitted" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="edit" runat="server" CausesValidation="false" CommandName="editForm"
Text="Edit" OnDataBinding="btnEdit_DataBinding" OnClick="btnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="delete" runat="server" CausesValidation="false" CommandName=""
Text="Delete" OnDataBinding="btnDelete_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="formID" />
</Columns>
</asp:GridView>
protected void btnEdit_Click(object sender, System.EventArgs e)
{
Session["formID"] = gvHistory.SelectedDataKey.Value;
Label1.Text = Session["formID"].ToString();
}
If you are using CommandName with your item template then You can simply use Row_Command event, you don't need to create separate handler for button click.
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editForm")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
string value=grdView.DataKeys[row.RowIndex].Values["myDataKey"].ToString();
}
}
Button btn = (Button)sender;
GridViewRow gvrow = (GridViewRow)btn.NamingContainer;
if (gvrow != null)
{
//Get the Row Index
int rowIndex = gvrow.RowIndex;
//Get the DataKey value
Session["formID"] = gvHistory.DataKeys[rowIndex].Value.ToString();
Label1.Text = Session["formID"].ToString();
}

Categories