I have a GridView in ASP.NET page. The GridView is bound to a dataset/datatabe. One of the columns of the grid is a command button and the gridview has method OnRowCommand (e.g. OnRowCommand="GridView_RowCommand") specified.
When user clicks on the button in the grid, the method GridView_RowCommand fires. I would like to find the index to the DataTable for the row where button was clicked. Note, that I am not looking for index to the GridView row but rather the index to the DataTable bound to the GridView.
Thank you in advance for your help.
You have a few options and it depends on the amount of data you are binding to the gridview, one you could save the dataset/datatable to Session[""] as you bind or you could retrieve the data from the database again once you have the unique id of the row. You could create the following on your gridview:
<asp:GridView ID="gvCustomer" runat="server"
AutoGenerateColumns="False" DataKeyNames="yourId" onrowcommand="gvCustomer_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkAction" runat="server" Text="Do Something" CommandName="yourEvent" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then in the code behind for the RowCommand event have:
protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "yourEvent")
{
var row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int rowId = Convert.ToInt32(gvCustomer.DataKeys[row.RowIndex]["yourId"]);
}
}
At this point you have the id which you could either query the database again or access the data source object that you save in to session before binding to the gridview
Or another alternative is:
<asp:LinkButton CommandArgument='<%#Eval("PrimaryKey")%>' />
Then you can get the arg with e.CommandArgument in the gvCustomer_RowCommand method
Related
this is for ticketing system where the tickets are in different status like 'open, rejected, closed, resolved..'
In asp.net i have a gridview and in the gridview there are textboxes and a dropdownlist.
i can get output from the database and get to populate it in the gridview and also the contents in the dropdown list are also displayed.
how can i get to bind the data of the dropdownlist in the grid to that of the output of the query. if the ticket is closed it should select closed, if the ticket is rejected it should select rejected.
in the onrowCommand, i fetch data from another table and populate into the dropdown list. this is the full list of status like 'oopen, rejected, closed, resolved..'
Your question is missing details like what markup you have used for gridview and also what code you have for RowDataBound event.
So, I have provided a sample answer that you can easily adapt to your situation.
I am assuming you have a gridview with an id of GridView1 that contains the following ItemTemplate ( other columns have been omitted since they are not needed to understand this approach).
You should have a hidden field in the template so you can store the current status of the row; also when you are binding your gridview you should be getting a column called Status for the row.
Sample Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText = "Status">
<ItemTemplate>
<asp:HiddenField ID="hfStatus" runat="server" Value='<%# Eval("Status") %>' />
<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Then in your RowDataBound event where you are binding the dropdown for the row, you need to get the value of hidden field hfStatus and then set the selected item of dropdown using this value.
I have assumed that a method called GetStatusDropDownListData is there that gets the data for binding dropdown list.
Sample RowDataBound event
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlStatus = (e.Row.FindControl("ddlStatus") as DropDownList);
ddlStatus.DataSource = GetStatusDropDownListData();
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
//Select the Status in DropDownList
string currentStatus = (e.Row.FindControl("hfStatus") as HiddenField).Value;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;
}
}
i had used this code and its working now:
in asp file:
' Visible = "false" />
in the .cs file
string currentStatus = (e.Row.FindControl("lblStatus") as Label).Text;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;
I'm trying to populate a single text box (or parameter) with data from a gridview column when I click on a button in that row.
Gridview gets it data from a sqlconnection
the gridview is
| Drawing |
| 12345 | VIEW
| 12346 | VIEW
the VIEW is a template button with an onclick event, when the user clicks the button the data from the Drawing column (12345) should be passed to ether a textbox or a paremeter. (this is the part I dont know how to do) once the Iv got the number in a textbox I can use it as pareameter and then a pdf is opened of that drawing, I have code for this and is working.
thanks for any help
If you are using C#, the simplest thing to do would be to add an in-built select command button to the gridview rows at runtime. Then on the selectedindexchanged event of the gridview simply access the cell of the selected row that you want the value from. You can then assign that string to anything you want. Like so:
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string myString = myGridView.SelectedRow.Cells[4].Text.ToString();
TextBox1.Text = myString;
}
Remember that the cell index collection is zero based, so [0] is actually the first cell in the row.
Use TemplateFields and the grid view's OnRowCommand event, like this:
Markup:
<asp:gridview id="GridView1"
OnRowCommand="GridView1_RowCommand"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxDrawing" runat="server"
Text="<%# Eval("Drawing")) %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="selc" runat="server" Text="View"
CommandName="View"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected 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 == "View")
{
// Convert the row index stored in the CommandArgument
// property to an integer
var index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection
var row = GridView1.Rows[index];
// Find the drawing value
var theDrawingTextBox = row.FindControl("TextBoxDrawing") as TextBox;
// Verify the text box exists before we try to use it
if(theDrawingTextBox != null)
{
var theDrawingValue = theDrawingTextBox.Text;
// Do something here with drawing value
}
}
}
How can I get the selected item on the SelectedIndexChanging handler when using two SelectCommands? I can get the selected row through e.SelectedRow but I'm unable to get the selected column.
It's correct to have more than one SelectCommand in a GridView? If not, what's the best way?
You don't select a column in a gridview, you select a row. If you want a particular field of a row to be "selectable" you might consider using a HyperLinkField or a ButtonField and handle the events for that. But to my knowledge, admittedly it's limited, there is no way to be able to know, purely with a GridView and its SelectedRow Property which field in the row was "selected" when the row was selected.
You don't have to use select commands. you can use template fields and add a named command to it then you can check which of them was clicked in the RowCommand event (and u can also get the row index as well) see below.
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"
CommandName="MyCommand" Text="Button" CommandArgument='<%# Container.DataItemIndex %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
RowCommend Event below
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand"))
{
int row = Int32.Parse(e.CommandArgument.ToString());
}
}
i have added a button control in gridview and i want to redirect
to the another page on button's click event,
and also i want to access the values of selected row in a gridview and show that values on other page on button
click event which is inside the gridview,, can anybody plz help me out in this .
this should be helpful: http://msdn.microsoft.com/en-us/library/bb907626.aspx
for accessing values inside RowCommand event find your row first (by index):
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = MyGridView.Rows[index];
and then controls inside it which holds the values you need:
Label MyLabel= (Label)row.FindControl(MyLabel);
after that all you need to do is to transfer to your page and send values from your controls with it (do that with querystring):
Server.Transfer("MyPage.aspx?value="+MyLabel.Text)
here you can read more about gridview RowCommand event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
You need to add either a ButtonField or a TemplateField with a button inside and then you can add your code to the RowCommand and use the e.CommandName and e.CommandArgument
To redirect you can use Response.Redirect(address)
To see the values it depends where in the program you want to do it. If during databinding you can use the dataitem("column"). Outside of databinding you can go through the Gridview.Rows collection for the row you want and then look at the row.Cells(columnNumber).Text to see the value.
we have an event in gridview called, gridview rowcommand event, in that you can write the code for redirecting to another page using button. First you have to bind the value of which you want to pass in button property called commandargument.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("abc.aspx?id=" + e.CommandArgument);
//here id means passing the value using querystring to another page.
}
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name" DataField="fullname" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClick="btnDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// This focuses the current row where the button lies. you can perform all events of server-controlls
//instead of Button e.g LinkButton, Dropdownlist index changes...
protected void btnDelete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
string id = gvRow.Cells[0].Text;
string name = gvRow.Cells[1].Text;
//use these values in query string or any logic you prefer for cross page posting
Response.Redirect("your URL ?id=" + id + "&name=" + name);
}
hi I have this gridview like this.
<asp:DropDownList ID="triggerDropDown" runat="server" AutoPostBack="true" onselectedindexchanged="triggerDropDown_SelectedIndexChanged">
<asp:GridView ID="myGridView" run="server">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
<asp:DropDownList ID="myDropDown1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column 2">
<ItemTemplate>
<asp:DropDownList ID="myDropDown2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
now, when I change my triggerDropDown I want to change also all of the DropDowns inside Column 1 how can I do that?
protected void triggerDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
// what should I do here?
}
Inside your event method you should access the DropDownList that resides within each row of the GridView. Doing this you can bind each DropDownList to whatever data you want.
This link shows you how to do that:
http://www.velocityreviews.com/forums/t191319-need-help-with-accessing-a-control-within-a-template-field.html
Basically:
Iterate over each row of your GridView;
Find the DropDownList control with something like:
DropDownList mddl = GridView.Rows[2].FindControl("myDropDown1");
Bind new data to mddl.
The gridview is very likely not what you want here. The way to change the value of a control contained in a row is usually through grabbing a handle to the desired control using e.Item.FindControl() from within the ItemDataBound event of the gridview.
The problem with your approach is that you're wanting a control outside of the gridview (triggerDropDown) to interact with a single row of the gridview. Do you want the first row, first column, last row, first column or first column for each of the items in the grid? It's probably better you take the target of your trigger dropdown and place it outside of the gridview and deal with it directly.
If you really intend to change items in a row in the grid consider doing so in the ItemDataBound event of the gridview and you'll find lots of examples out there.
Actually I can use GridViewRow :) I just have to find the GridViewControl and get its Rows attribute which is a GridViewRow and now I can do a foreach of each row.
foreach (GridViewRow gridViewRow in (this.FindControl("myGridView") as GridView).Rows)
{
// I can see all elements of my row here as if I am traversing on GridViewEvents
}