I have an ASP.NET GridView control with two asp:CommandField columns that are both using the Select command to perform different tasks. How do I distinguish which column was selected in the OnRowCommand event when both return "Select" when I check the CommandName property of the GridViewCommandEventArgs object?
Here is my source code:
ASPX page:
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowCommand="MyGridView_OnRowCommand">
<Columns>
<asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" />
<asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="No Click Me!" />
</Columns>
</asp:GridView>
Code behind:
protected void MyGridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
string x = e.CommandName //returns "Select" for both asp:CommandField columns
}
Use a button column instead that way you can specify the specific command names and work with it from there
<asp:ButtonField ButtonType="Link" Text="Click Me" CommandName="MyCommand1" />
<asp:ButtonField ButtonType="Link" Text="No Click Me" CommandName="MyCommand2" />
Then you can take action based on e.CommandName
Use the GridViewCommandEventArgs.CommandArgument property !
Well, first do you HAVE to use SELECt as the command? You could set that to something else that makes more sense.
Secondly, you could set the CommandArgument property to different values so you know which one is being clicked.
use the command argument property.
e.commandargument
Or you can dynamically create the button in the command field and set the commandName to anything you want.
in gridview_Load
for (int i = 0; i <= GridView1.Rows.Count - 1; i++) {
linkbutton btnedit = new linkbutton();
GridView1.Rows(i).Cells(3).Controls.Add(btnedit);
//the above is where you want the button to be on the grid
btndel.CommandName = "Select2";
btndel.CommandArgument = "whatever you want";
}
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Select1" Then
//do stuff
End Sub
The answer you seek is simple and tricky. I had that problem too in my website project, so I surfed the internet for days and not found what I and you were needed.
One day I just thought about the problem alone and made experiments for hours and finally realized that the only easy way to know the column that the button was clicked is in the RowCommand event of the GridView in the CommandName property of the GridViewCommandEventArgs. More correctly probably and comfortable is to edit columns of GridView through the design mode and replace your Command fields to Button fields.
You can give any string/text you want to each button field in its CommandName, so in the RowCommand event you can know which was clicked. Button1 or Button2, but you don't want to give these strings, because you request something that the buttons should select and give to you, so the CommandName should be the word select, but it can be SELECT too and Select and selecT and etc.
The select command can be mention in the CommandName in many forms, and still the system will recognize it. So for example if you have two Button fields in the GridView, whose first CommandName is simply select and the other is SELECT, then when any of them is clicked the RowCommand event raises and
if (e.CommandName == "select")
{
Label1.Text = "You clicked first button";
}
else
{
Label1.Text = "You clicked second button";
}
and the SelectedDataKey of your GridView will contains the data you requested. What other people offered in their answer to differ in CommandName by setting button one to select_one and setting button two to select_two will help you to know if either select_one was clicked or other, but the SelectedDataKey of your GridView will remain null or DataKey instance that doesn't contain the information you need at all.
In other words, the buttons will not select any necessary information, so it is very important to follow my answer. It is the exact, perfect and great solution to your problem!
Related
I have a gridview looks like below.
Name Attended_Exam
Raj English
Hindi
Das Korea
Rahul Spanish
English
And the query used to bind datatable to this gridview contains a submission_id. Which is unique for each student and his subject.
Each attended exam name is shown as a linkbutton. Now, when clicking on it, I want to get the Submission_id of each subject. What is the best way to achieve this?
<asp:GridView ID="gvSubmissionHeaders" runat="server" AutoGenerateColumns="true"
Width="80%" OnRowDataBound="gvSubmissionHeaders_RowDataBound"
Font-Bold="false" RowStyle-Height="30px" >
</asp:GridView>
protected void gvSubmissionHeaders_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //for adding linkbutton to Attended_Exam
//loop through the cell.
for (int j=1;j< e.Row.Cells.Count;j++)
string[] arrLinks =null;
if (!string.IsNullOrEmpty(e.Row.Cells[j].Text.ToString()) && e.Row.Cells[j].Text.ToString()!= " ")
{
arrLinks = e.Row.Cells[j].Text.Split(',');
}
if(arrLinks!=null)
{
for (int i = 0; i < arrLinks.Length; i++)
{
LinkButton btnLink = new LinkButton();
btnLink.ID = "Id" + arrLinks[i] + i;
btnLink.Text = arrLinks[i] + "<br>";
e.Row.Cells[j].Controls.Add(btnLink);
}
}
}
Ok, the detail here is that you could have simply noted that you have cell/colum in the grid, and you might add 1 or maybe 4 link buttons into that cell. So you have "N" buttons that you add, and you need/want particular information from that button.
If the button was static (a single link button), then you can add custom attributes to that button, and even additional columns data (ones not displayed in the grid) like this:
<td align="center" >
<asp:LinkButton ID="pUploadFiles" runat="server"
CommandArgument='<%# Eval("ID")%>' CommandName='cmdView'
Width="120px" align="center"
ContactNameID = '<%# Eval("ContactNameID")%>'
QuoteNum = '<%# Eval("QuoteNum")%>'
ProjectHeaderID = '<%# Eval("ID")%>'
>
</asp:LinkButton>
</td>
So now when you get the sender, or do a findcontrol, you can do this in code:
Dim btn As LinkButton ' we get required data from btn on row.
btn = lvd.FindControl("pUploadFiles")
With btn.Attributes
Session("ContactID") = .Item("ContactNameID")
Session("ContactGeneralID") = .Item("ContactGeneralID")
Session("QuoteNum") = .Item("QuoteNum")
End With
So linkbtn.Attributes.Item("my custom value") will get you any extra values (columns) that you attached to that link button. And with the above eval(), you can even pull any column from the data source as long as those column exist in the datatable/datasource that drives the listview or gridview. (the great part here is that you don't need actual columns in the gridview/listview to try and store and "hide" these values. The extra values are simply part of that given control as custom attributes.
Now you are adding the link btn in code, but you can do the same thing.
eg:
LinkButton btnLink = new LinkButton();
btnLink.ID = "Id" + arrLinks[i] + i;
btnLink.Text = arrLinks[i] + "<br>";
btnLink.Attributes.Add("Submission_id","100");
e.Row.Cells[j].Controls.Add(btnLink);
Now of course you would replace the hard coded "100" in above with the value you are pulling or want to store as a custom attribute. So you can add 1 or "many" custom attributes to that link button. When the click on that link button, then you grab/get the additional attributes that are associated with that link button by using Mybtn.Attributes.Item("Submission_id").
So be it one link button that is part of the grid, you can add those extra attributes (without even extra code), and even rows from the databind that are not in the grid.
So I can have several buttons, and when they click, then additional information such as PK row, or even several other values can be part of (or added) to that one button. And in your case this should work fine if you dynamic adding 1 or 5 buttons as you are. So, those additonal values you want can simply become additonal attributes of that button.
Edit:
Ok, the problem is that controls that require events that are created "after" the page has been rendered cannot really be wired up. You would have to move the code to a earlier event. So you are free to add controls, but they will in "most" cases be rendered TOO LATE to have events attached. Thus when you click on the link button, nothing fires.
So there are two solutions I can think of that will work.
First, set the control to have a a post back URL, and include a parameter on that post back.
eg this:
Dim lnkBtn As New LinkButton
lnkBtn.Text = "<br/>L" & I
lnkBtn.ID = "cL" & I
lnkBtn.PostBackUrl = "~/GridTest.aspx?r=" & bv.RowIndex
If you put a PostbackUrl, then when you click on the button, the page will post back. However, the grid row events such as rowindex change, or row click event etc. will NOT fire. So, if you willing to have a parameter passed back to the same page as per above, then you can pass the 1-3 (or 1-N) values you have for each control.
Of course that means you now have a parameter on the web page URL (and users will see this). You of course simply pick up the parameter value on page load with the standard
Request.QueryString["ID"] or whatever.
However, another way - which I think is better is to simple wire up a OnClickClick() event in js, and thus do this:
I = 1 to N
Dim lnkBtn As New LinkButton
lnkBtn.Text = "<br/>L" & I
lnkBtn.ID = "cL" & I
lnkBtn.OnClientClick = "mycellclick(" & I & ");return false;"
Now in above note how I am passing "I" to the js routine. You would pass your 200, 300 or whatever value you want.
then you script will look like this:
<script>
function mycellclick(e) {
__doPostBack("MySelect", e);
}
</script>
So above simply takes the value passed from the cell click (and linkbutn), and then does the postback with a dopostback. I used "MySelect", and you can give that any name you want.
Now, in the on-load event, you can simply go like this:
If Request("__EVENTTARGET") = "MySelect" Then
Dim mypassvalue As String = Request("__EVENTARGUMENT").ToString
Debug.Print("row sel for MySelect = " & mypassvalue)
End If
So, you are 100% correct - clicking on those controls does NOT fire server side event, and they are wired up too late for this to occur. so you can and often do say add some columns or controls to a gridview, but they are created and rendered TOO LATE for the events to be wired up (and thus they don't fire when clicked on).
But, you can add a postback to the lnkbutton, and you can also add a OnClickClick() event (JavaScript function call) and they will both work. I don't like parameters in the URL appearing when you click, so I think the js script call as per above works rather nice.
So while in the comments I noted (and suggested) that you have to set the CommandName="Select". This suggesting still holds true (without CommandName = select, then the rowindex will not fire. You can't use just ANY name - it MUST be select. However this ONLY works if the control is part of the grid and not added on the fly. As noted, it might be possible to move the grid event to "earlier" event (page initialize) but it going to be a challenge and will require you to re-organize the page. The most clean, and one that does not require parameters in the URL is adding that js OnClientClick() event. You can however set the controls postbackurl and along with a parameter in the URL, and that also can work well if you open to URL with parameters (I don't like them).
First you declare your table column ID on the DataKeyNames on GridView eg:
<asp:GridView DataKeyNames="cTableColumnID" ID="gvSubmissionHeaders" runat="server" ...
Then you can get this ID per Row using this line
gvSubmissionHeaders.DataKeys[CurrectRowNum]["cTableColumnID"]
I want to preface this by saying that I am a beginner to asp.net, especially when it comes to working with the FormView controls. I have searched long and hard and have spent hours debugging this issue.
I have 3 FormViews on one aspx page. Each FormView has its own EditItemTemplate and PagerTemplate with DefaultMode="Edit". I am not using a SqlDataSource, but instead databinding programatically on the PageLoad when if(!Page.IsPostBack) and also calling the databinding method when the PageIndexChanging method is called. The pager template contains a 'Back' and a 'Next' button set with CommandArgument="Prev" and CommandArgument="Next", respectively, and both set with CommandName="Page".
The paging works great on the first FormView. When I hit the back or next button, it pages (i.e. re-binds) appropriately. During the 1st FormView's paging event, I also successfully call the binding methods for the 2nd and 3rd FormView since I want them to bind data that is specific to the page selected in the 1st FormView.
But, when I page back to the first page of the 1st FormView (i.e. PageIndex = 0), and then try to page forward in the 2nd FormView, the datakey for the 1st FormView is null. In fact, the formview1.DataSource is null for the 1st FormView when I try to click a navigation button on the 2nd FormView.
Then, here's where I thought it was weird, ... if I click back a second time on the 1st FormView, THEN the formview1.DataSource is fine, and I can then navigate in the 2nd FormView.
All viewstates for the formviews and the buttons are set to true.
I have tried calling formview1.DataBind() inside formview2's paging event before any paging occurs but no success there. I have also tried setting properties: UseSubmitBehavior="False" and CausesValidation="False" on the paging buttons. Admittedly, I did this without really understanding the behavior but rather implemented after seeing it suggested in solutions for other somewhat related problems.
The templates are rather long since there are many fields in each. But the FormView tags look like this:
<asp:FormView ID="fvHeader" runat="server" DataKeyNames="ObjectID" DefaultMode="Edit" AllowPaging="True" OnModeChanging="fvHeader_ModeChanging" OnPageIndexChanging= "fvHeader_PageIndexChanging">
<EditItemTemplate> ..... </EditItemTemplate> </asp:FormView>
PagerTemplates:
<PagerSettings Mode="NextPrevious" />
<PagerTemplate>
<span class="labels">Page: <%#fvHeader.PageIndex+1%> of <%#fvHeader.PageCount %></span>
<asp:Button ID="btnBack" runat="server" CommandArgument="Prev" CommandName="Page" CssClass="btnHdr" Text="<< Back" />
<asp:Button ID="btnNext" runat="server" CommandArgument="Next" CommandName="Page" CssClass="btnHdr" Text="Next >>" /> </PagerTemplate>
Note that 'fvHeader' is what I'm calling 'formview1' for simplicity in my question.
Back/Next buttons C# code and databinding the 1st formview:
protected void fvHeader_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
fvHeader.PageIndex = e.NewPageIndex;
bindFV_Initial();
//rebind fvSub1 (2nd formview) to get the 1st obs of the newly selected header record
fvSub1.ChangeMode(FormViewMode.Edit);
fvSub1.PageIndex = 0;
bindSub1_Initial();
//rebind 2nd subform
fvSub2.ChangeMode(FormViewMode.Edit);
fvSub2.PageIndex = 0;
bindSub2_Initial();
}
private void bindFV_Initial()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
if (dtEOS == null || dtEOS.Rows.Count == 0)
{
sqlda = new SqlDataAdapter("USE dbWEF SELECT * FROM tblHeader WHERE [UserID] = '" + Session["User"] + "' AND [ProjectName] = '" + Session["Project"] + "'", conn);
sqlda.Fill(dtEOS);
}
fvHeader.DataSource = dtEOS;
fvHeader.DataBind();
conn.Close();
if (dtEOS.Rows.Count > 0)
{
fillDD_fvHeader(); //Fill dropdowns and databind ddls
}
}
}
Below is the error message I receive when I attempt to navigate the 2nd formview.
Error in: bindSub1_Initial.
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Collections.Specialized.OrderedDictionary.get_Item(Int32 index)
at System.Web.UI.WebControls.DataKey.get_Item(Int32 index)
at RenewableEnergyDataEntry.Forms.EagleObservationSurvey.bindSub1_Initial()
During debugging, I find that this error occurs right when the 2nd formview is being binded because the datatable is empty which is a result of it needing the datakey from formview1 to pull the correct data, which again, is null because formview1's datasource goes to null. But clicking formview's back button one more time, refills and KEEPS the datasource, thereby allowing formview2 to fill and navigate perfectly. So strange...
I suggest you simplify you code.
more than likely you are creating conflicts with the view state.
We can't see where and how your dataSource: (dtEOS) is being defined.
But I am going to guess that it's being reset conditionally on a call back.
This is a common problem in ASP.net (conflict with view sate and /or databinding).
Try using a grid instead of a formview and it will handle the paging much more gracefully without needing a postback and data rebind.
I've a gridview with client ID, client name, client contact number and a hyperlink to client detail.
I would like to pass selected clint ID to another asp page (clientDetail.aspx & ClientContact.aspx).
I'm thinking of passing the clientID as session. But how do i go about doing this? Can someone guild me on this as im quite new to this.
& how do i use the passed data in clientDetail.aspx & ClientContact.aspx?
Thanks in advance for your help.
Add two new columns of type HyperLinkField to your gridView as follows. Now clientID is passed as QueryString. One link is here
<asp:HyperLinkField DataNavigateUrlFields="ClientID"
DataNavigateUrlFormatString="~/ClientDetails.aspx?id={0}"
Text="Client Details" />
Assuming that you are selected the grid row with a button or link button you could use the OnRowCommand event
When you wire into this event you can pick out the value you want from the selected item then save it into the Session which will then be available for subsequent pages. In the below exampel I've assumed the value is in a label field so you can pick it out of that control.
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblMyValue = (Label)e.Row.FindControl("lblMyValue");
Session["myValue"] = lblMyValue .Text;
}
}
There are other variants of this for instance you could store the value you are interested in in the CommandArgument property of the button that you use to select the row. The command argument will then be available in the RowCommand event
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string arg = e.CommandArgument;
//.. put into session here
}
And there are alternatives using different events for instance you could use the DataKeys collection of the GridView to store the value you are interested in and pick out the value from there
Markup fragment
<asp:gridview id="CustomersGridView"
//.. more properties
datakeynames="myID"
onselectedindexchanged="MyGridView_SelectedIndexChanged"
runat="server">
Code behind
void MyGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = MyGridView.SelectedIndex;
Session["myValue"] = CustomersGridView.DataKeys[index].Value.ToString();
}
There are a number of alternatives to get this working. I would use the first one detailed if it were me - I've always found it easiest to get to work. You can make the label hidden with Css if you want - if it isn't suitable for the UI. Or use a hidden field (with runat="server"). I'm going to stop - I'm risking confusuing by just typing on.
You should be able to evaluate the clientid field of the asp.net gridview in the navgiate url of the hyperlink and pass it as a query string like so:
<asp:gridview id="OrdersGridView"
datasourceid="OrdersSqlDataSource"
autogeneratecolumns="false"
runat="server">
<columns>
<asp:boundfield datafield="ClientID"
headertext="Client ID"/>
<asp:boundfield datafield="ClientName"
headertext="Client Name"/>
<asp:boundfield datafield="ClientContact"
headertext="Client Contact"/>
<asp:hyperlinkfield text="Details..."
navigateurl="~\details.aspx?clientid='<%# Eval("ClientID") %>'"
headertext="Order Details"
target="_blank" />
</columns>
</asp:gridview>
I am displaying a gridview which should display a column containing image button.
How can I add image button to gridview row dynamically?
I don't want to enter by using template field from design field of the gridview. As this is image button I should be able to capture the event of the same.How to do the same?
i think you can add image to your edit and delete buttons from .aspx file also, i just tried and got it..
1.firstly make the gridview and then add activities like OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting"
i ma showing you jow to add images to edit and delete button for "update" and "cancel" you can proceed in the same way..
now go to source of gridview..
you will see code like this
<asp:CommandField ShowEditButton="True"/>
<asp:CommandField ShowDeleteButton="True"/>
after that change few things like add
<asp:CommandField ShowEditButton="True" ButtonType="Image" EditImageUrl="~/uploads/edit.png" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Image" DeleteImageUrl="~/uploads/delete.png" />
And after that make sure to save your images in 45 * 25 sizes only , and save it in any folder and remember to specify the path as i have done here , my folder is uploads.
Note: don't store images in App_data , it is for storing .mdf database files , any images will not work for you.. if the images is not showing in drop down list while adding imageurl try to add its path physically.
I think you can use template field for this. What you have to do is at the GridView RowDataBound event find the ImageButton you added in the template field and then give an ID or Row number or something which you can use to identify which row the ImageButton is in, as an Attribute of the ImageButton.
You can use this place to give the ImageUrl as well a sample would look like the below one.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgbtn = (ImageButton)e.Row.FindControl("imgbtn1");
if (imgbtn != null)
{
imgbtn.Attributes["id"] = e.Row.RowIndex.ToString();
}
}
}
then you can create the click event for ImageButton. In that you can get the id/rowindex of the image button which was clicked and do what ever you want. Event may look like the below
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
string rowindex = btn.Attributes["id"];
}
then in the GridView template field you can add the click event to ImageButtons onClick event. This may look like the below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton runat ="server" ID="imgbtn1" onclick="ImageButton1_Click"/>
</ItemTemplate>
</asp:TemplateField>
I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.
So I decided to add a button that would retrieve the URL only when you clicked the button.
Here's my GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.
Does anyone know what the issue is?
Why use a dynamic button at all? You can easily put the linkbutton directly into the markup of the gridview (as long as you don't mind using a template field) and there will be no need to mess around with the RowDataBound event.
Your markup would look something like the following:
<Columns>
<asp:TemplateField HeaderText="SomeHeaderText">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn" runat="server" CommandName="NumClick" CommandArgument= '<%# (string)Eval("dbValue") %>' Text='<%# (string)Eval("dbValue") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
</Columns>
Add breakpoints to the RowCommand event and make sure that you can hit the breakpoints.
The problem may lie elsewhere.
Also, make sure that you're not databinding on postback.
You have a big trouble with your code. It's pretty hard for me to explain what's your big mistake, but I can easily tell you how to fix.
The problem is that you generate a new button inside the RowDataBound event, definitely the wrongest choice. The button gets rendered because it exists after that event when page renders, but doesn't exist before data binding. If you bind data everytime you load the page (even during postback) the button still gets rendered because you generate a new button.
But since the button doesn't exist before data binding, it cannot raise events. You must declare the button from markup into a template of GridView, then access it not by using new LinkButton() but by using e.Row.Cells[0].FindControl("buttonId") and set its text. Then, you have to set its markup in order to fire its own Command event (not RowCommand) and handle it as you used (don't forget to set CommandArgument during data binding)
[Edit] I also made a mistake: controls inside data bound controls also don't exist before data binding. But they are initialized not with new Control() (by the private methods of data bound control) but with Page.LoadControl(typeof(Control)). That's the first thing you must fix when you load controls dynamically!!
Because the control is added dynamically on databind and you have to databind the gridview for each postback, the control being "clicked" is different each time. The event doesn't fire because at the time it needs to fire it doesn't exist as it did in the last iteration of the page.
I notice you don't have any logic determine if the button should be there, and it always goes into cell[0].
You should place this button into a TemplateItem so that it exists properly. If you have a need to do it in code-behind, you are probably better served doing it in the RowCreated event.