Command argument string is empty in rowcommand event c# - c#

I have a gridview. Inside it I have a link button. I want to get the row index of the button which was clicked inside the rowcommand event handler. This can be done using the command argument property. however it is returning empty string and there by getting an exception.
This is the line present inside event handler
Int indexval = Convert.ToInt32(e.commandArgument.ToString());
I've also tried this to get row index.
Inside aspx page:
commandArgument= <%#container.DataItem%>
But this also returns empty string
Tried like this in rowcommand event
Gridview gr = (gridview)sender;
Int Ind = gr.rows.selectedIndex.
Here Ind value shows as -1
There are some questions on this but all are in VB.net
I want the solution to this to be in c#.
PS I'm new to c# and asp.net

I use CommandField
Add this CommandField to your GridView <Columns>...</Columns>
<asp:CommandField ShowSelectButton="true" SelectText="View/Edit" ItemStyle-Width="60" />
This ties in to GridView_SelectedIndexChanging which gives you the RowIndex:
protected void gvCategories_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int rowIndex = e.NewSelectedIndex;
}

Related

Make GridView AutGenerateColumn a LinkButton that fires RowCommand event

Simple question which my searches seem to be coming up blank on.
I have a GridView that is AutoGeneratingColumns=True
This generates a column "MyColumn". I would like to make this columns value a clickable LinkButton that fires the RowCommand event of the GridView with a specific CommandNmae and the cells value as the CommandArgument.
I'm trying to do this without using a custom ItemTemplate, I know how to do that. I'm hoping i can pragmatically modify a auto generated column in the GridView as described.
Tia
This can be done in the OnRowDataBound event of the GridView.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the current row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
///create a new linkbutton
LinkButton button = new LinkButton();
button.Text = "LinkButton";
button.CommandArgument = "MyArgs";
//assign a command to the button
button.Command += Button_Command;
//add the button to cell x
e.Row.Cells[3].Controls.Add(button);
}
}
Because you are adding control dynamically, the binding of the GridView should NOT be wrapped inside an IsPostBack check. Something you would do normally.

Get a hidden field in Gridview on RowCommand Event

If I have two buttons on gridview and each performing different function. For example my code below,
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
errorlab.Text = row.Cells[3].Text;
}
}
The value of cell 3 is a hidden field and there is a value in the database that's binding to hidden field but with my code I couldn't get the value. The errorlab label is showing nothing. Maybe I'm missing something.
I would like to suggest an answer, the command argument will not fetch you the row index. Instead it will give you what you bind during gridview data binding.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
//The hidden field id is hdnProgramId
HiddenField hdnProgramId = (((e.CommandSource as LinkButton).Parent.FindControl("hdnProgramId")) as HiddenField);
}
}
This will try to locate the hidden field from the gridview row context.
If you have futher controls on the gridview cell then you have to access them using the Controls property
HiddenField hiddenField =row.Cells[3].Controls[0] as HiddenField;
if(hiddenField != null)
errorlab.Text = hiddenField.Value;
You have to use the correct index for the controls. Debug the code and check what is position of the control in row.Cells[3].Controls.
Always try to avoid referring cells by it's index position in gridview as it may result in changing the code if you happen to add/delete few more columns in the grid in the future which might result in undesired result. Also note that hiddenfield does not have a Text property but rather a Value property to access it's value.
If you know the hiddenfield's name then better try accessing it by it's name. Let's say you have your hiddenfield defined as below in your gridview
<ItemTemplate>
<asp:HiddenField ID ="hdnField" runat="server" Value='<%# Bind("ErrorLab") %>'/>
</ItemTemplate>
Then in your GridView1_RowCommand you can do
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
HiddenField hdnField = (HiddenField)row.FindControl("hdnField");
errorlab.Text = hdnField.Value;

Session in not passed between pages c#

I'm working with VS 2013 and Mysql, in one of my pages I put select query in a gridview in this view and I have a button for each row so that if I press a row button I have a new window opening that has the colum Id (which is the first colum ) from the gridview.
the grid view button code:
<Columns>
<asp:TemplateField ><ItemTemplate><asp:Button ID="gridbutton" runat="server" Text="Plus de détails" OnClientClick="basicPopup();return false;" RowIndex='<%# Container.DisplayIndex %>' OnClick="button_click" /></ItemTemplate></asp:TemplateField>
</Columns>
the code of the button_click method:
protected void button_click(object sender, EventArgs e)
{
Button gridbutton = sender as Button;
int rowIndex = Convert.ToInt32(gridbutton.Attributes["RowIndex"]);
string n = "l'index" + rowIndex + "";
Session["idProjet"] = GridView1.Rows[rowIndex].Cells[2].Text;
//string idProjet = Convert.ToString(Session["idProjet"]);
// Alert.Show(idProjet);
}
I just used the two last lines to make sure that I'm getting the value, and I'm getting the right value.
And this is the code from the second page where I want to get the session value:
protected void Page_Load(object sender, EventArgs e)
{
string idProjet = Convert.ToString(Session["idProjet"]);
Alert.Show(idProjet);
}
But all I'm getting is an empty result.
In you button code you have both onclientclick and click event.
In you clickclick event I guest you are opening the different page. Note that client click executes first. So the new page already gets opened. Your server side event executes later. That is why the session is not available in the new form.
<asp:Button ID="gridbutton" runat="server" Text="Plus de détails" OnClientClick="basicPopup();return false;" RowIndex='<%# Container.DisplayIndex %>' OnClick="button_click" />
In this case you have to pass the idProject as query string to the new page.

Cant get value of cell on gridview nested in formview

I have a formview and a nested gridview where i would like to be able to select the value of a specific cell when the row has been updated. I took the example code from the msdn site as it's close to what i want:
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView SprayGrid = (GridView)FormView1.FindControl("GridView1");
int Index = SprayGrid.EditIndex;
GridViewRow row = SprayGrid.Rows[Index];
TextBox message = (TextBox)FormView1.FindControl("TextBox1");
message.Text = row.Cells[4].Text;
}
However, for some reason this will only pick up the index of the cell, i.e. if i change the row.cells[0] i can see in my message box the index number if i want to see any other cell then the message is blank? Any ideas would be great.
Use DataKeys on the GridView, and instead of trying to set the TextBox value from the cell, set it from the DataKey.
In the ASPX:
<asp:GridView Id="GridView1" runat="server" DataKeyNames="SomeColumnName">
And in your row updating event:
TextBox message = (TextBox)FormView1.FindControl("TextBox1");
message.Text = SprayGrid.DataKeys[row.RowIndex]["SomeColumnName"].ToString();

Passing Control Id from Linkbutton in a gridview

How do I pass the Control ID in a gridview that is derived from a stored procedure into a variable. I will use the variable to pass into the database later on to return some results. Thanks.
var controlId = ((LinkButton)gridView1.Rows[0].FindControl("lbName")).Id;
Are you trying to do something like the above?
Update
You can use the OnSelectedIndex event of the GridView to find the row that was select.
void GridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
var controlId = ((LinkButton)row.FindControl("lbName")).Id;
}
I tend to use the CommandName and CommandArgument fields with LinkButtons in a GridView.
The CommandName represents the name of the command, so that you can have more than one linkbutton that do different things and the CommandArgument is the Database ID or other point of reference for the command.
You need to subscribe to the RowCommand event handler on the GridView

Categories

Resources