Binding value to textbox inside of gridview - asp.net

I have problems with binding a value of a field inside a gridview to a textbox which is inside the gridview as well. I'm intending to do this for editing the table.
I tried to do this with eval and bind, but the textbox won't show the values and I have absolutely no clue why.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Eval("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
The thing is that it works fine inside the ItemTemplate, but doesn't inside the EditItemTemplate-element. Really no clue what the problem is.
Code behind:
Sub gvBS_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles gvBS.RowEditing
gvBS.EditIndex = e.NewEditIndex
End Sub
Sub gvBS_RowCancelingEdit() Handles gvBS.RowCancelingEdit
Me.gvBS.EditIndex = -1
gvBS_DataBind()
End Sub

I assume that the GridView enters never edit-mode since you aren't handling the RowEditing event or you didn't DataBind it after you've set gvBS.EditIndex = e.NewEditIndex;.
<asp:GridView
OnRowEditing="gvBS_RowEditing" OnRowCancelingEdit="gvBS_RowCancelingEdit"
ID="gvBS" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" SkinID="gvWithoutWidth">
codebehind (BindGrid is the method which databinds your grid):
protected void gvBS_RowEditing(object sender, GridViewEditEventArgs e)
{
gvBS.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void gvBS_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvBS.EditIndex = -1;
BindGrid();
}
You should also remember to databind it only on the first load, not on consecutive postbacks when ViewState is enabled(default). Therefore you can check the page's IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

Try the Bind instead of Eval in EditItemTemplate like this
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Bind("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>

Related

asp.net editable gridview "no data found" row causes issue after postback

I have a simple problem with my gridview. It is an editable gridview which allows inserting, updating and deleting rows. It is bound to a datatable. I store the datatable in the viewstate and bind the datatable on page_load for every postback. There is no column order or paging and I only have a few records on this gridview. When there is no data to display, I add an empty message text like "no data found" manually to grid. It is okey for the first page_load. But after postback, this text disappears, but the row is still there. And the main problem is the row has "edit" and "delete" command columns after postback. This row should not have edit or delete columns after postback. It works really fine before postback.
This problem never happens if there is at least one row in gridview.
If I have at least one row, then if I add more rows: No problem
If I have the empty grid, then I add a row (before any postback for example combobox value change): No problem
If I have the empty grid: then I do a postback by changing a value in a combobox, then "no rows found" message in the grid disappearing and there is an extra row in the grid which has no text and has edit and delete columns
If I have the grid with that unwanted row, then I add a row to that gridview: The unwanted row is going away and new row appearing on the grid. No problem
So the only problem is that extra row which is appearing after postback.
Code details are below. Please help me with this silly problem. I couldnt solve it for days.
ASPX:
<asp:GridView ID="grdTerminals" runat="server"
AutoGenerateColumns="False" DataKeyNames="TRM_ID"
OnRowCancelingEdit="grdTerminals_RowCancelingEdit"
OnRowDataBound="grdTerminals_RowDataBound"
OnRowEditing="grdTerminals_RowEditing"
OnRowUpdating="grdTerminals_RowUpdating" ShowFooter="True"
OnRowCommand="grdTerminals_RowCommand"
OnRowDeleting="grdTerminals_RowDeleting"
HeaderStyle-BackColor="#73be1e" HeaderStyle-ForeColor="Window" HeaderStyle-Font-Bold="true" Width="500px" HeaderStyle-Height="30">
<Columns>
<asp:TemplateField HeaderText="Terminal" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="ddlTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTerminal" runat="server" Text='<%# Eval("TRM_MNMC") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TAS No" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewTASNo" runat="server" Width="120"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Kaydet"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert" Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="" ShowDeleteButton="True" ShowHeader="True" DeleteText="Delete"/>
</Columns>
</asp:GridView>
C#
// I am storing the data in ViewState
DataTable dtTerminals
{
get
{
return ViewState["_dtVehicleTerminals"] as DataTable;
}
set
{
ViewState["_dtVehicleTerminals"] = value;
}
}
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (dtTerminals == null)
{
dtTerminals = new DataTable();
dtTerminals.Columns.Add("TRM_ID");
dtTerminals.Columns.Add("TRM_MNMC");
dtTerminals.Columns.Add("TAS_NO");
}
if (!IsPostBack)
{
string VhcId = Request["vhc_id"];//Edit mode
if (!string.IsNullOrEmpty(VhcId))
{
BindTerminalInfo(VhcId);
}
else
{
//To show empty grid
BindTerminalGrid();
}
}
// Bind Terminal Info
void BindTerminalInfo(string VhcId)
{
dtTerminals = VehicleManager.GetVehicleTerminals(VhcId);
BindTerminalGrid();
}
//Bind Terminal Grid
public void BindTerminalGrid()
{
if (dtTerminals.Rows.Count > 0)
{
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
}
else
{
//Show No Records Found
dtTerminals.Rows.Add(dtTerminals.NewRow());
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
grdTerminals.Rows[0].Cells.Clear();
grdTerminals.Rows[0].Cells.Add(new TableCell());
grdTerminals.Rows[0].Cells[0].Text = "No Data found";
dtTerminals.Rows.Clear();
}
}
//Other methods related to grid functionality
protected void grdTerminals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlTerminal = (DropDownList)e.Row.FindControl("ddlTerminal");
if (ddlTerminal != null)
{
ddlTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlTerminal.DataBind();
ddlTerminal.DataTextField = "TRM_MNMC";
ddlTerminal.DataValueField = "TRM_ID";
ddlTerminal.SelectedValue = grdTerminals.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlNewTerminal = (DropDownList)e.Row.FindControl("ddlNewTerminal");
ddlNewTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlNewTerminal.DataBind();
}
}
protected void grdTerminals_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblId = (Label)grdTerminals.Rows[e.RowIndex].FindControl("lblTrmUnqId");
DropDownList ddlTerminal = (DropDownList)grdTerminals.Rows[e.RowIndex].FindControl("ddlTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.Rows[e.RowIndex].FindControl("txtTASNo");
dtTerminals.Rows[e.RowIndex]["TRM_ID"] = ddlTerminal.SelectedValue;
dtTerminals.Rows[e.RowIndex]["TRM_MNMC"] = ddlTerminal.SelectedItem;
dtTerminals.Rows[e.RowIndex]["TAS_NO"] = txtTASNo.Text;
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string TrmId = Convert.ToString(grdTerminals.DataKeys[e.RowIndex].Values[0]);
dtTerminals.Rows.Remove(dtTerminals.Rows[e.RowIndex]);
BindTerminalGrid();
}
protected void grdTerminals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
DropDownList ddlNewTerminal = (DropDownList)grdTerminals.FooterRow.FindControl("ddlNewTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.FooterRow.FindControl("txtNewTASNo");
DataRow dr = dtTerminals.NewRow();
dr["TRM_ID"] = ddlNewTerminal.SelectedValue;
dr["TRM_MNMC"] = ddlNewTerminal.SelectedItem.Text;
dr["TAS_NO"] = txtTASNo.Text;
dtTerminals.Rows.Add(dr);
BindTerminalGrid();
}
}
protected void grdTerminals_RowEditing(object sender, GridViewEditEventArgs e)
{
grdTerminals.EditIndex = e.NewEditIndex;
BindTerminalGrid();
}
I am not sure it is the correct solution . But try adding Empty data text property of Gridview.
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
emptydatatext="No data in the data source."
runat="server">
<emptydatarowstyle backcolor="LightBlue"
forecolor="Red"/>
</asp:gridview>
Or try like this
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgBtnUpdate" runat="server" Height="32px"
ImageUrl="~/Images/Update.jpg" ToolTip="Update" Width="32px" CommandName="Update"/>
<asp:ImageButton ID="imgBtnDelete" runat="server" Height="32px"
ImageUrl="~/Images/delete.gif" style="margin-left: 0px" ToolTip="Delete"
Width="32px" CommandName="Delete"/>
<asp:ImageButton ID="imgBtnCancel" runat="server" Height="32px"
ImageUrl="~/Images/Cancel.png" ToolTip="Cancel" Width="32px" CommandName="Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/AddNew.gif"
ToolTip="Add New Record" CommandName="Add"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" Height="32px"
ImageUrl="~/Images/pencil.png" ToolTip="Edit" Width="32px" CommandName="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
Finally I have fixed this problem. The solution is adding
if (!Request.Form["__EVENTTARGET"].Split('$').Contains(grdTerminals.ID))
{
BindTerminalGrid();
}
code block to If(Postback) statement. I should rebind data for everypostback but only if the control which caused postback is not the "datagrid".

How to find Grid view button click event?

Button btnAddrecord = (Button)sender;
GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer;
if (btnAddrecord.CommandName == "onAddMaterial")
Define the button in your grid view markup and assign a CommandName value to the button, like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Add Record">
<ItemTemplate>
<asp:Button ID="btnAddRecord"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"
CommandName="AddRecord" runat="server" Text="Add" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle the OnRowCommand event and AddRecord command, like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddRecord")
{
// Get index of row passed as command argument
int index = Convert.ToInt32(e.CommandArgument.ToString());
// Your logic here
}
}
1.Give a command name for button..
2.Then inside gridview
if e.commandname="yourcommandname"
{
//your code..
}
<!--We use onrowcommand for getting the selected row -->
<asp:GridView runat="server" ID="gvTest" AutoGenerateColumns="False" OnRowCommand="gvTest_OnRowCommand" >
<Columns>
<asp:TemplateField HeaderText="BookId" >
<ItemTemplate>
<asp:Label runat="server" ID="lblBookId" Text='<%# Bind("[BookId]") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtBookId" Text='<%# Bind("[BookId]") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" CommandArgument="<%# Container.DisplayIndex %>" CommandName="IsDelete" Text="Delete"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
//Code Behind
protected void gvTest_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//getting rowindex which we have selected by using CommandArgument
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "IsDelete")
{
int bkid = gvTest.Rows[rowindex].Cells[0].FindControl("BookId");
//call a method to delete book using the bkid
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}

retrieve data from gridview row to an asp.net form

I would like to retrieve a row from the gridview by clicking on ImageButton (Booking):
here is the code of my grid view:
<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText=" Booking">
<ItemTemplate>
<asp:ImageButton ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" PostBackUrl="form.aspx"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Trade" HeaderText="Trade" SortExpression="Trade" />
<asp:BoundField DataField="CARRIER" HeaderText="CARRIER"
SortExpression="CARRIER" />
</Columns>
</asp:GridView>
The textbox of the form.aspx page that should be filed from the gridview row:
<asp:TextBox ID="trade" runat="server" CssClass="input , focus"></asp:TextBox>
<asp:TextBox ID="carrier" runat="server" CssClass="input , focus"></asp:TextBox>
Add GridView RowCommand event and command argument for image button where you can pass an id or something to determine the current row.
<asp:GridView onrowcommand="gvRowCommand" ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:ImageButton CommandArgument='<%# Eval("SomeId") %>' ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" />
</ItemTemplate>
C#
protected void gvRowCommand(object sender, GridViewCommandEventArgs e)
{
var someId = e.CommandArgument;
}
VB.Net
Protected Sub gvRowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
Dim someId As Integer = Convert.ToInt32(e.CommandArgument)
End Sub
You can refer msdn for more : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

Get data from the row of a Dropdown in a Gridview

I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="MatrĂ­cula" runat="server" Text="MatrĂ­cula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.

RowCommand not firing when clicking buttons inside TemplateField

Basically I have a GridView:
<asp:GridView ID="gvServices" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowSorting="True"
AutoGenerateColumns="False" OnRowCommand="gvServices_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
And inside I have 2 TemplateFields:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnStart" runat="server" Text="Start" CommandName="StartService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnStop" runat="server" Text="Stop" CommandName="StopService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
Finally I have the method thats supposed to fire when clicking on either of the Buttons on the gridView, problem is that when I click either of them the event does not get called at all
public void gvServices_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "StartService")
{
StartServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
}
if (e.CommandName == "StopService")
{
StopServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
}
loadGridView();
}
RowCommand on GridView does fire from a button within a TemplateField. Check out the answer to this thread:
Linkbutton inside a gridview not firing
You need to listen to the buttons RowCommand. GridView.RowCommand is used when you have an asp:ButtonField on each row.
Aspx code:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnStart" runat="server" Text="Start" OnCommand="GridButtons_Command" CommandName="StartService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnStop" runat="server" Text="Stop" OnCommand="GridButtons_Command" CommandName="StopService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
Code Behind:
public void GridButtons_Command(object sender, CommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "StartService")
{
StartServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
}
if (e.CommandName == "StopService")
{
StopServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
}
loadGridView();
}

Resources