I have a RadGrid that contains a template column in which I've put two image buttons for edit and delete actions.
<telerik:GridTemplateColumn HeaderText="Actions">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/icon_edit.png" style="display: inline-block" ToolTip="Edit" /> <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/images/icon_delete.png" style="display: inline-block" ToolTip="Delete" />
</ItemTemplate>
</telerik:GridTemplateColumn>
How would get the value of the first cell of the row (datafield = "User_ID") when I click on the "delete" button?
Step 1.
Go to the Radgrid itself and edit the field DataKeyNames="" (under MasterTableView) and add the datafield you are pulling:
<MasterTableView ... DataKeyNames="User_ID">
Step 2.
Edit the CommandName="" property of the Imagebuttons located in the grid:
<asp:ImageButton ID="btnDelete" runat="server" style="display: inline-block" ToolTip="Delete" CommandName="dosomething"/>
Create the following method for your Radgrid and add this code:
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "dosomething")
{
//Use a line of code here to save that User_ID that you want from the first column
theUserId = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["User_ID"];
}
}
Make sure theUserId = the same Type (int,double,dec...) as the field it's pulling from or you will have to parse it:
theUserId = Int.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["User_ID"]);
Let me know if you need more help.
Please check Below code snippet.
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridBoundColumn DataField="Name" HeaderText="Name" UniqueName="Name">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" ToolTip="Edit" CommandName="Edit" /> <asp:Button
ID="btnDelete" runat="server" ToolTip="Delete" CommandName="Delete" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
.........................
protected void grdCompCliente_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
GridDataItem item = e.Item as GridDataItem;
string ID = item.GetDataKeyValue("ID").ToString();
string Name = item["Name"].Text;
}
else if (e.CommandName == "Delete")
{
GridDataItem item = e.Item as GridDataItem;
string ID = item.GetDataKeyValue("ID").ToString();
string Name = item["Name"].Text;
}
}
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 want to extract the article id from a gridview row when I click on the hyperlink. My goal is to be able to capture the article id field of a specific row when I click on the hyperlink in gridview.
This is what I tried so far but for some reason, it doesn't go to the codebehind when I click on the hyperlink.
<asp:GridView ID="Rssfeed" runat="server" AutoGenerateColumns="false" onrowcommand="grid_RowCommand" CssClass="Grid">
<Columns>
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
Articleid:
<asp:Label ID="Label1" Text='<%#Eval("articleid") %>' runat="server" />
<br />
Title :
<asp:Label ID="Label2" Text='<%#Eval("title") %>' runat="server" />
<br />
Link:
<asp:HyperLink ID="hlnkFile" runat="server" target="_blank" CommandName="Select" NavigateUrl='<%# Eval("link") %>' Text='<%# Eval("link") %>'></asp:HyperLink> <br />
Publicationdate:
<asp:Label ID="Label3" Text='<%#Eval("publicationdate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public void grid_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = Rssfeed.Rows[index];
}
}
This example can help:
<ItemTemplate>
Link:
<asp:LinkButton ID="lbFile" CommandName="Select" runat="server"><%# Eval("link") %></asp:LinkButton>
</ItemTemplate>
code behind
public void Rssfeed_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
// get text from LinkButton e.g. URL as in question
string link = ((LinkButton)selectedRow.FindControl("lbFile")).Text;
// Redirect to the URL link
Response.Redirect(link);
}
}
This is a simple gridView I m using in aspx web page
<asp:GridView ID="Order" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="none"
ItemType="MyProject.Models.TempList" SelectMethod="GetList" >
<Columns>
<asp:BoundField DataField="ItemID" HeaderText="ID" SortExpression="ItemID" />
<asp:TemplateField HeaderText="ItemName">
<ItemTemplate>
<asp:Label runat="server" ID="ItemName" Width="40" Visible="true" text="<%#: Item.Item.ItemName %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price(each)">
<ItemTemplate>
<%#: String.Format("{0:c}", Convert.ToDouble(Item.Item.UnitPrice))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<div style="float:left">
<asp:Button ID="DeleteBtn" runat="server" Text="Delete" OnClick="DeleteBtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have 2+ items in a list<> which is populating the gridView, how can I tell (in the codeBehind.cs) that which Row the "DeleteBtn" was clicked on?
I was using a for loop to iterate every item in gridView using Rows[i] and used a check box to know which item wants to be deleted using a Update button.
But I want to do it directly on a custom created deletebutton.
Thanks in advance, I know I'm missing something silly.
The best way to do that is using CommandName and CommandArgument in your button declaration like that
<asp:Button ID="AddButton" runat="server" CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Add to Cart" />
you can pass any value in the case we pass the rowIndex, you can get a propertie from your object like that CommandArgument="<%# Eval("id") %>" after that you will handle the onRowCommand method
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
hope it helps :)
Use the button's CommandArgument property; assign Container.DataItemIndex to it. Then use the OnRowCommand event of the gridview and grab the index.
Sample aspx:
<asp:Label runat="server" ID="lblMsg" />
<asp:GridView runat="server" id="gvSample" AutoGenerateColumns="false" OnRowCommand="PerformOperation">
<Columns>
<asp:BoundField DataField="RowValue"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandName="MyCustomCommand" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
gvSample.DataSource = Enumerable.Range(0, 10).Select(i => new { RowValue = i });
gvSample.DataBind();
}
protected void PerformOperation(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyCustomCommand")
{
var rowIndex = int.Parse(e.CommandArgument);
lblMsg.Text = string.Format("Button on row index: {0} was clicked!", rowIndex);
}
}
Let the button field be given a CommandName, say for example a unique string myCommandName in the Edit columns dialog box. Don't worry about the CommandArgument. Then, in the Grid view Row command event, you can check which button (i.e. column) is clicked by tracing the command name like if e.commandname = "mycommandname", at the same time the CommandArgument will also be available as String and all we have to do is to converttoint32, something like intSelectedRow = convert.ToInt32(e.CommandArgument) which will give us the selected row's index.
Here is the scenario ..
I have a GridView with columns ID, Name, and Type. Name is click enabled and will redirect to other page. The entire row can be selected, and using jQuery I changed its background so it will be recognized as selected row.
The reason it must be selected is because a link, for example Delete is present at the page. When Delete is clicked, it should delete the selected row but when there is no selected row, it should do nothing.
Here is my code:
<asp:LinkButton ID="btnDelete" runat="server">Delete</asp:LinkButton>
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound" OnRowCommand="gridView_Command" AutoGenerateColumns="false" >
<columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</columns>
</asp:GridView>
public void gridView_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "NameButton")
{
var id = e.CommandArgument;
// redirect to edit page //
}
}
I am using jQuery to indicate that a row is selected.
I already have the code for the Delete event method but my problem is how can I tell the compiler that a row is currently selected upon clicked of Delete?
I am thinking of using a hidden field, and on jQuery, I will set the value of the hidden field to the ID of the row that is selected. However, I still don't have the idea on how to do it.
It is pretty straight. You can store the SelectedIndex in a hidden field and find the GridViewRow by the index.
Add a hidden field in the markup and also attach an event method to the Link button:
<asp:LinkButton ID="btnDelete" OnClick="btnDelete_Click" runat="server">Delete</asp:LinkButton>
<asp:HiddenField ID="hdnIndex" runat="server" />
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound"
OnRowCommand="gridView_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</Columns>
</asp:GridView>
In the GridView RowDataBound add an attribute to execute javascript to save index in hidden field:
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript: getElementById('" + hdnIndex.ClientID + "').value='" + e.Row.RowIndex + "';");
}
}
And LinkButton's click event do like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
int index = 0;
int id = 0;
if (int.TryParse(hdnIndex.Value, out index))
{
GridViewRow gvr = gridView.Rows[index];
if (gvr != null && int.TryParse(gvr.Cells[0].Text, out id) )
{
// id is available here
// do wahtever you want with the id
// even you can delete the record from db by id
}
}
}
I guess command-argument is what you are searching for...Check this link
You just need to pass the Id using command argument from front-end to the code file and from there you can delete it easily.
I'm trying to populate multiple text boxes with data from a gridview when I click the link button (which is in fact the name of one of the fields in each row) but it isn't going through. I'm new to this - literally my first time. Any help would be most appreciated.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
AccountNumber.Text = selectedRow.Cells[1].Text;
Name.Text = selectedRow.Cells[1].Text;
Address1.Text = selectedRow.Cells[1].Text;
Address2.Text = selectedRow.Cells[2].Text;
Address3.Text = selectedRow.Cells[3].Text;
PhoneNumber.Text = selectedRow.Cells[4].Text;
FaxNumber.Text= selectedRow.Cells[5].Text;
CurrencyID.Text = selectedRow.Cells[6].Text;
}
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="Agent_Account_No"
DataSourceID="SqlDataSource1"
AlternatingRowStyle-BackColor ="Lavender"
HeaderStyle-BackColor="#9966FF"
AllowSorting="True" HeaderStyle-BorderColor="Black"
HorizontalAlign="Center"
RowStyle-BorderColor="Black"
EmptyDataText="There are no data records to display."
onrowcommand ="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCFFCC" />
<Columns>
<asp:BoundField datafield="Agent_Account_No" HeaderText="Account No"
ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="50"
SortExpression="Agent_Account_No"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"
Width="50px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I got it to work this way - using help from this site:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = GridView1.DataKeys[row.RowIndex]["Agent_Account_No"].ToString();
......
}
I don't know if this declaration is right, but it works. However now that it works I see a problem that I didn't see before - see my profile and thanks a lot!
I would highly recommend using TemplateFields for all of your columns, like this:
Markup:
<Columns>
<asp:TemplateField HeaderText="Account No" SortExpression="Agent_Account_No">
<ItemTemplate>
<asp:Label ID="LabelAccountNumber" runat="server"
Text='<%# Eval("Agent_Account_No") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now in the RowCommand method, you can use the FindControl() method of the grid view row to get to the text you are interested in, like this:
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// Find the account number label to get the text value for the text box
Label theAccountNumberLabel = selectedRow.FindControl("LabelAccountNumber") as Label;
// Make sure we found the label before we try to use it
if(theAccountNumberLabel != null)
{
AccountNumber.Text = theAccountNumberLabel.Text;
}
// Follow the same pattern for the other labels to get other text values
}
}