There is a RadGrid inside which there is a RadComboBox and asp Button in
EditItemTemplate.
Below is the current code:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClient="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
When I type/key-in something inside RadComboBox and click on asp Button,
then only the searching related to key-in text starts and display after execution of OnClick event of asp Button.
Now, the new requirement came to place RadButton(with - Single Click
approach) in place of asp Button, to avoid double click.
Problem is: when I implement RadButton inside EditItemTemplate of RadGrid, RadButton never postback i.e., when I click on it nothing happens.
But same RadButton when I use outside of RadGrid, is working fine.
Below is the code using RadButton(with - Single Click
approach):
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<telerik:RadButton runat="server" ID="btnSearch" Text="Search" SingleClick="true"
SingleClickText="Submitting..." OnClick="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
Please let me know why is this hapenning?
Please do reply
Thanks in advance
I would recommend you to use CommandName as button event. Anyway here is my code... I tried use OnClick and CommandName it work perfectly fine. I suspect your error will be some sort of javascript...
.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" Width="100%"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView EditMode="InPlace">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("T")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="rcb" runat="server" AllowCustomText="true">
</telerik:RadComboBox>
<telerik:RadButton runat="server" ID="btnSearch" Text="Search"
SingleClick="true" SingleClickText="Submitting..." CommandName="Search" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<telerik:RadButton ID="btnEdit" runat="server"
Text="Edit" CommandName="Edit"></telerik:RadButton>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadButton ID="btnCancel" runat="server" Text="Cancel"
CommandName="Cancel"></telerik:RadButton>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("T");
// Loop & Add
for (int i = 0; i < 10; i++)
dt.Rows.Add(i + "");
// Check & Bind
if (dt != null)
{
ViewState["Grid"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
// Dispose
dt.Dispose();
}
}
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = ViewState["Grid"] as DataTable;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("GG");
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "Search")
{
// Variable
GridEditableItem item = e.Item as GridEditableItem;
string something = "";
// Find Control
RadComboBox rcb = item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
// Set
something = rcb.Text;
// Do Something
Response.Write(something);
}
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridEditableItem)
{
// FindControl
RadComboBox rcb = e.Item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
rcb.DataSource = ViewState["Grid"] as DataTable;
rcb.DataTextField = "T";
rcb.DataValueField = "T";
rcb.DataBind();
}
}
}
Related
Please can someone point me in the right direction, i have a radcombobox inside the radgrid, as soon as i edit the row it loses it's value
<telerik:GridTemplateColumn DataField="SupplierRegion" UniqueName="SupplierRegion" HeaderText="Region">
<ItemTemplate>
<asp:HyperLink runat="server" ID="SupplierRegionHyperlink" Text='<%# Eval("SupplierRegion")%>'></asp:HyperLink>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox runat="server" ID="SupplierRegionRadComboBox" EnableLoadOnDemand="true" AutoPostBack="true" >
<WebServiceSettings Method="GetRegions" Path="~/WebServices/SuppliersWS.asmx"></WebServiceSettings>
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
and the below is my C# code
if (e.CommandName == "Edit")
{
GridEditCommandColumn editColumn = (GridEditCommandColumn)SupplierSearchGrid.MasterTableView.GetColumn("EditCommandColumn");
if (!editColumn.Visible)
editColumn.Visible = true;
GridEditableItem item = (GridEditableItem)e.Item;
RadComboBox SupplierRegionValue = (RadComboBox)item.FindControl("SupplierRegionRadComboBox");
SupplierRegionValue.SelectedValue = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["RegionID"].ToString();
SupplierRegionValue.Text = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Description"].ToString();
}
in my edit it can't seem to find the Combobox as it returns null
Take a look at topic How to bind data to radcombobox inside grid EditItemTemplate
XAML
<telerik:GridTemplateColumn DataField="SupplierRegion" UniqueName="SupplierRegion" HeaderText="Region">
<ItemTemplate>
<asp:HyperLink runat="server" ID="SupplierRegionHyperlink" Text='<%# Eval("SupplierRegion")%>'></asp:HyperLink>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox runat="server" ID="SupplierRegionRadComboBox" EnableLoadOnDemand="true" AutoPostBack="true" >
<WebServiceSettings Method="GetRegions" Path="~/WebServices/SuppliersWS.asmx"></WebServiceSettings>
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridEditCommandColumn FooterText="EditCommand footer" UniqueName="EditCommandColumn"
HeaderText="Edit" HeaderStyle-Width="100px" UpdateText="Update">
</telerik:GridEditCommandColumn>
C#
protected void gvSupplierRegion_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem myGridItem = (GridDataItem)e.Item;
if (myGridItem.IsInEditMode)
{
RadComboBox combo = (RadComboBox)myGridItem["SupplierRegion"].FindControl("SupplierRegionRadComboBox");
combo.DataSource = GetUploadStatus();
combo.DataTextField = "Value";
combo.DataValueField = "Key";
combo.DataBind();
combo.SelectedValue = DataBinder.Eval(myGridItem.DataItem, "UploadStatus").ToString();
}
}
so for these with the same issue i found the solution
in the aspx page add the the webservice's id and description colum id in the datakeynames, then in your radcombobox in the edititemtemplate
<telerik:GridTemplateColumn DataField="SupplierRegion" UniqueName="SupplierRegion" HeaderText="Region">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"Description")%>'
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox runat="server" ID="SupplierRegionRadComboBox" AllowCustomText="false" EnableLoadOnDemand="true" AutoPostBack="true" Text='<%#Bind("Description") %>' >
<WebServiceSettings Method="GetRegions" Path="~/WebServices/SuppliersWS.asmx"></WebServiceSettings>
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
and in the code behind
protected void SuppliersSearchRadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem editItem = (GridEditableItem)e.Item;
RadComboBox combo = (RadComboBox)editItem.FindControl("SupplierRegionRadComboBox");
combo.SelectedValue = DataBinder.Eval(editItem.DataItem, "RegionID").ToString();
}
}
I have an ASP.NET datagrid with a few rows in it. I'd like some of the rows to be editable, but not all of them (based on a particular data item in that row).
Originally, I was doing this with a ButtonColumn, but I wasn't able to turn that on or off for specific rows.
Here's what I have now:
<asp:DataGrid ID="grid1" runat="server" AutoGenerateColumns="false" EnableViewState="true" CssClass="GridviewControlStyle" CellSpacing="0" CellPadding="4" HeaderStyle-CssClass="HeaderStyle"
OnEditCommand="grid1_EditCommand" OnUpdateCommand="grid1_UpdateCommand" OnCancelCommand="grid1_CancelCommand" OnItemDataBound="grid1d_ItemDataBound">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<strong><%# Resources.Status %></strong>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container, "DataItem.STATUS") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderTemplate>
<strong><%# Resources.Amount %></strong>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container, "DataItem.AMT") %>
</ItemTemplate>
<EditItemTemplate>
<asp:CustomValidator ID="cvAmountGrid" OnServerValidate="cvAmountGrid_ServerValidate" Display="None" runat="server" ControlToValidate="txtAmount" />
<asp:TextBox ID="txtAmount" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.AMT") %>' CssClass="small" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" ID="btnEdit" Visible='<%# IsRowEditable(Eval("STATUS").ToString()) %>' CommandName="Edit" />
<asp:Button runat="server" Text="Update" ID="btnUpdate" Visible="false" CommandName="Update" />
<asp:Button runat="server" Text="Cancel" ID="btnCancel" Visible="false" CommandName="Cancel" />
</ItemTemplate>
</asp:TemplateColumn>
</asp:DataGrid>
Code Behind:
public bool IsRowEditable(string status)
{
return !status.Equals("Locked", StringComparison.OrdinalIgnoreCase);
}
protected void grid1_EditCommand(object source, DataGridCommandEventArgs e)
{
grid1.EditItemIndex = e.Item.ItemIndex;
grid1.DataBind();
TextBox t = e.Item.FindControl("txtAmount") as TextBox;
t.Visible = true; //this can't be found
Button b = e.Item.FindControl("btnEdit") as Button;
b.Visible = false;
Button u = e.Item.FindControl("btnUpdate") as Button;
u.Visible = true;
Button c = e.Item.FindControl("btnCancel") as Button;
c.Visible = true;
}
There are a few problems I've run into with this approach. Firstly, calling DataBind seems to reset the visibility status I've set on any buttons. If I don't databind, then my editable column doesn't show as editable. So, I try to set the textbox to be editable manually; but findcontrol returns null so I can't. What am I doing wrong here?
Another way to achieve it;
There I removed data validation and column name data binders to avoid
complexities. You can try below with them.
Update and cancel buttons are under EditItemTemplate so they will appear at edit event.
.ASPX
<asp:DataGrid ID="grid1" runat="server" AutoGenerateColumns="false" EnableViewState="true" CssClass="GridviewControlStyle" CellSpacing="0" CellPadding="4" HeaderStyle-CssClass="HeaderStyle"
OnEditCommand="grid1_EditCommand" OnUpdateCommand="grid1_UpdateCommand" OnCancelCommand="grid1_CancelCommand" OnItemDataBound="grid1d_ItemDataBound">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<strong>Status</strong>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container, "DataItem.STATUS") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderTemplate>
<strong>Amount</strong>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container, "DataItem.AMT") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.AMT") %>' CssClass="small" ReadOnly="false"/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" ID="btnEdit" Visible='<%# IsRowEditable(Eval("STATUS").ToString()) %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button runat="server" Text="Update" ID="btnUpdate" CommandName="Update" />
<asp:Button runat="server" Text="Cancel" ID="btnCancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
Code Behind
There you don't have set the visibility manually. EditItemTemplate will handle it at the edit event and when the user clicks cancel or update the Edit template will be replaced with the view.
I used some hardcoded list of Data Items and you can replace it with actual data source and try.
List<DataItem> t;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
t = new List<DataItem>();
DataItem t1 = new DataItem() { AMT = 5, STATUS = "LOCKED" };
DataItem t2 = new DataItem() { AMT = 15, STATUS = "OPEN" };
DataItem t3 = new DataItem() { AMT = 25, STATUS = "OPEN" };
DataItem t4 = new DataItem() { AMT = 35, STATUS = "LOCKED" };
t.Add(t1);
t.Add(t2);
t.Add(t3);
t.Add(t4);
grid1.DataSource = t;
grid1.DataBind();
}
protected void grid1_UpdateCommand(object sender, DataGridCommandEventArgs e)
{
string newAmount = (e.Item.Cells[1].FindControl("txtAmount") as TextBox).Text;
//Update the data source with edited data
grid1.EditItemIndex = -1;
//Load Data with updated data
LoadData();
}
protected void grid1_CancelCommand(object sender, DataGridCommandEventArgs e)
{
grid1.EditItemIndex = -1; //Bring back the previous state
LoadData();
}
public bool IsRowEditable(string status)
{
return !status.Equals("Locked", StringComparison.OrdinalIgnoreCase);
}
protected void grid1_EditCommand(object source, DataGridCommandEventArgs e)
{
grid1.EditItemIndex = e.Item.ItemIndex;
LoadData();
}
protected void grid1d_ItemDataBound(object sender, DataGridItemEventArgs e)
{
}
DataItem.cs
public class DataItem
{
public int AMT { get; set; }
public string STATUS { get; set; }
}
Okay, I figured out a better way to do this. I added the code below to my markup for all three buttons:
Visible='<%# IsRowEditing(Container.ItemIndex) %>'
In my code behind, I checked to see if the row was currently being edited, and used that to control the visibility of the buttons:
protected bool IsRowEditing(int index)
{
return index > 0 && index == grid1.EditItemIndex;
}
This fixed all my issues and was much simpler than what I was trying to do previously. Databinding also works with this method.
I am trying to insert new item in RadGrid using ItemCommand event. But unable to close the Edit Form after this.
Here is code in my aspx-
<telerik:RadGrid ID="rgItems" Skin="Metro" runat="server" AutoGenerateColumns="false" Width="100%"
AllowAutomaticInserts="true"
MasterTableView-CommandItemSettings-ShowRefreshButton="false"
OnNeedDataSource="rgItems_NeedDataSource" OnItemCommand="rgItems_ItemCommand">
<MasterTableView CommandItemDisplay="Top" AllowAutomaticInserts="true" CommandItemSettings-ShowAddNewRecordButton="true">
<EditFormSettings EditFormType="Template">
<FormTemplate>
<asp:Panel ID="pnlNewItem" runat="server" DefaultButton="btnInsert">
<div class="form-group">
<asp:TextBox ID="txtClass" runat="server" CssClass="form-control" placeholder="Enter Class" Text='<%# Eval("Class") %>'></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtWeight" runat="server" CssClass="form-control" placeholder="Enter Weight" Text='<%# Eval("Weight") %>'></asp:TextBox>
</div>
<div class="box-footer">
<asp:Button ID="btnCancel" runat="server" Text="Cancel" class="btn btn-default" CommandName="Cancel" />
<asp:Button ID="btnInsert" runat="server" class="btn btn-info pull-right"
CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
Text='<%# (Container is GridEditFormInsertItem) ? "Add Item" : "Update" %>' />
</div>
</asp:Panel>
</FormTemplate>
</EditFormSettings>
<Columns>
<telerik:GridTemplateColumn HeaderText="Class">
<ItemTemplate>
<asp:Label ID="lblClass" runat="server" placeholder="Enter Class" Text='<%# Eval("Class") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Weight">
<ItemTemplate>
<asp:Label ID="lblWeight" runat="server" placeholder="Enter Weight" Text='<%# Eval("Weight") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Here is code in ItemCommand event-
protected void rgItems_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
DataTable dtItems_Global = new DataTable();
dtItems_Global.Columns.Add(new DataColumn("Class", typeof(string)));
dtItems_Global.Columns.Add(new DataColumn("Weight", typeof(string)));
if (rgItems.Items.Count > 0)
{
foreach (GridDataItem gdi in rgItems.Items)
{
DataRow drItem = dtItems_Global.NewRow();
drItem["Class"] = (gdi.FindControl("lblClass") as Label).Text;
drItem["Weight"] = (gdi.FindControl("lblWeight") as Label).Text;
dtItems_Global.Rows.Add(drItem);
}
}
switch (e.CommandName)
{
case "PerformInsert":
TextBox txtItemClass = (e.Item.FindControl("txtClass") as TextBox);
TextBox txtItemWeight = (e.Item.FindControl("txtWeight") as TextBox);
DataRow drItem = dtItems_Global.NewRow();
drItem["Class"] = txtItemClass.Text;
drItem["Weight"] = txtItemWeight.Text;
dtItems_Global.Rows.Add(drItem);
rgItems.Rebind();
break;
}
}
Can you include an empty edit column as show below in the columns markup of RadGrid? That is missing.
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
Also, after adding above markup, your code-behind for ItemCommand should also include following code.
protected void rgItems_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.InitInsertCommandName) //"Add Item" button clicked
{
GridEditCommandColumn editColumn = (GridEditCommandColumn)rgItems.MasterTableView.GetColumn("EditCommandColumn");
editColumn.Visible = false;
}
else if (e.CommandName == RadGrid.RebindGridCommandName && e.Item.OwnerTableView.IsItemInserted)
{
e.Canceled = true;
}
else
{
GridEditCommandColumn editColumn = (GridEditCommandColumn)rgItems.MasterTableView.GetColumn("EditCommandColumn");
if (!editColumn.Visible)
editColumn.Visible = true;
}
}
If above does not resolve it, then use the simple approach of code below in ItemInserted event.
e.KeepInInsertMode = false;
rgItems.EditIndexes.Clear();
rgItems.Rebind();
I would like to recommend using OnInsertCommand, OnUpdateCommand and OnDeleteCommand separately.
It is much more cleaner than using switch statement for each command.
<telerik:RadGrid ID="rgItems"
...
OnItemCommand="REMOVE THIS EVENT"
OnInsertCommand="rgItems_InsertCommand"
OnUpdateCommand="rgItems_UpdateCommand"
OnDeleteCommand="rgItems_DeleteCommand">
<MasterTableView CommandItemDisplay="Top" DataKeyNames="Id">
Make sure Id is the unique Id in your database - normally primary key.
</telerik:RadGrid>
protected void rgItems_InsertCommand(object source, GridCommandEventArgs e)
{
var item = e.Item as GridEditFormItem;
var txtClass= item.FindControl("txtClass") as TextBox;
// Insert to database - Do not need to call rgItems.Rebind(); here.
}
protected void rgItems_UpdateCommand(object source, GridCommandEventArgs e)
{
var item = e.Item as GridEditFormItem;
int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"]);
var txtClass= item.FindControl("txtClass") as TextBox;
// Update - Do not need to call rgItems.Rebind(); here.
}
protected void rgItems_DeleteCommand(object source, GridCommandEventArgs e)
{
int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"]);
// Delete - Do not need to call rgItems.Rebind(); here.
}
I'm trying to write a code that would update only one record for the data.
I do not need to be able to update every field on the row, only one particular field.
I have page that defines a GridView as following:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<UpdatePanel>
<ContentTemplate>
<fieldset style="width: 1%">
<legend>Search Customer</legend>
<table>
<tr>
<td>
<asp:DropDownList id="ddlSearchOption"
AutoPostBack="True"
OnSelectedIndexChanged="ddlSearchOption_SelectedIndexChanged"
runat="server">
<asp:ListItem Selected="True" Value="SearchBy"> Search By </asp:ListItem>
<asp:ListItem Value="CustID"> Customer ID </asp:ListItem>
<asp:ListItem Value="CustFirst"> First Name </asp:ListItem>
<asp:ListItem Value="CustLast"> Last Name </asp:ListItem>
<asp:ListItem Value="CustCity"> City </asp:ListItem>
</asp:DropDownList>
</td>
<asp:Panel id="pnlCustSearch" runat="server" >
<td>
<asp:Label id="lblEntry" runat="server" Text="" width="120px"></asp:Label>
</td>
<td>
<asp:TextBox id="txtSearchOptions" runat="server" width="50px">Hello</asp:TextBox>
</td>
<td>
<asp:Button id="btnFind" Text="Search" runat="server" onClick="btnFind_Click"></asp:Button>
</td>
</asp:Panel>
</tr>
</table>
</fieldset>
<div id ="msg">
<asp:Label id="lblMsg" runat="server" Text=""></asp:Label>
</div>
<div id="gridShow">
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red">
<Columns>
<asp:TemplateField Visible="true" HeaderText="Customer ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblCustID" Text='<%#Eval("CustID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("CustFirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName" Text='<%#Eval("CustLastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server" ID="lblCity" Text='<%#Eval("CustCity") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
<asp:Button runat="server" ID="btnUpdate" Text="Update" onClick="GridView1_btnUpdate_Click"/>
<asp:RequiredFieldValidator runat="server" ID="rfdCountry" ControlToValidate="txtEmail"
ValidationGroup="var1" ErrorMessage="*" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</UpdatePanel>
</asp:Content>
Then in codebehind I write the following:
protected void GridView1_btnUpdate_Click(Object sender, EventArgs e)
{
//Code goes here
}
When clicking button to update email nothing happens.
What am I doing wrong?
I tried to use one of suggestions here:
if (!IsPostBack)
{
GridView1.DataSource = App_Data.DataHandler.GetData("fname", "de");
GridView1.DataBind();
GridView1.Visible = true;
}
The data is displayed but the click event does not work anyway
I added the following to my GridView definition:
onrowcommand="GridView1_RowCommand"
and added the code suggested:
<asp:Button runat="server" ID="btnUpdate" Text="Update" CommandName="UpdateEmail"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
In my .cs file I added the following:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
Still, click event does not fire.
Ok, here is my code behind .cs file:
public partial class index : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Reset();
else
lblMsg.Text = "";
}
protected void Reset()
{
pnlCustSearch.Visible = false;
GridView1.Visible = false;
lblMsg.Text = "";
}
protected void ddlSearchOption_SelectedIndexChanged(object sender, EventArgs e)
{
Reset();
String ddlSelected = ddlSearchOption.SelectedValue;
if (ddlSelected != "")
{
ViewState["ddlSelected"] = ddlSelected;
pnlCustSearch.Visible = true;
SelectLabel(ddlSelected);
}
}
protected void SelectLabel(String choice)
{
switch (choice)
{
case "CustID":
lblEntry.Text = "Enter Customer ID";
break;
case "CustFirst":
lblEntry.Text = "Enter First Name";
break;
case "CustLast":
lblEntry.Text = "Enter Last Name";
break;
case "CustCity":
lblEntry.Text = "Enter City";
break;
default:
lblEntry.Text = "Enter Customer ID";
break;
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
String option = (String)ViewState["ddlSelected"];
String input = txtSearchOptions.Text.Trim();
GridView1.DataSource = DataHandler.GetData(option,input);
GridView1.DataBind();
GridView1.Visible = true;
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
protected void btnUpdate_Click(Object sender, EventArgs e)
{
String txt = null;
txt = "here";
}
}
When you try to handle events from GridView, you need to use a CommandName and a CommandArgument then handle the RowCommand event from the GridView.
See http://msdn.microsoft.com/... for reference.
ASP.Net page should look like :
<asp:ButtonField runat="server" ID="btnUpdate" Text="Update"
CommandName="UpdateEmail"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
In the RowCommand event :
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
I got it, finally. I had to change <asp:Button/> to
`<asp:ButtonField Text="Update Email" CommandName="UpdateEmail"`
and remove it from ItemTemplate.
But why this was a problem. What I wanted to do is just to display textfield in the same itemtemplate with button?
Actually, the answer was much easier then I thought originally. I just used different values to set session: __VIEWSTATE and VIEWSTATE
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
As soon as I changed it, button was able to fire events.
Thank you
i have a datalist and i set DataKeyField
<asp:DataList ID="lstItems" runat="server" RepeatDirection="Horizontal" DataKeyField="itemid" >
<ItemTemplate>
//contents in the datalist here
</ItemTemplate>
</asp:DataList>
i also have a imagebutton say imgADD in the page.My question is how can i get the value of datakey in imgADD click on server side
<asp:DataList ID="DataList_projects" runat="server" RepeatColumns="1" DataKeyNames="ID"
RepeatDirection="Horizontal" onitemcommand="DataList_projects_ItemCommand" >
<HeaderStyle ForeColor="Red" />
<ItemTemplate>
<hr style="color:" />
<asp:Label ID="ltlproject" ForeColor="#cc0000" runat="server" text="PROJECT:"></asp:Label> <b><u><asp:Label ID="lblProject" runat="server" Text='<%# Eval("TITLE")%>' ></asp:Label></u></b> <asp:LinkButton ID="lnkEdit" ForeColor="Red" CommandName="Edit" runat="server">Edit</asp:LinkButton><br />
</ItemTemplate>
</asp:DataList>
in your code behind
protected void DataList_projects_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
string strId = DataList_projects.DataKeys[e.Item.ItemIndex].ToString();
}
}
i think this will help you....
ASPX code:
//In the DataList ItemTemplate:
..
..
<asp:ImageButton ID="imgADD" runat="server" ImageUrl="uri" ToolTip="Add"
CommandName="Add" />
Code-behind:
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
if(e.CommandName == "Add")
{
string keyID;
// Get the index of the row from which this event was raised.
int idx = e.Item.ItemIndex;
// Get the DataKey with the same index.
object thisKey = DataList1.DataKeys(idx);
if(thisKey != null)
{
keyID = thisKey.ToString();
// do something here
}
}
}