is it possible to get CommandArgument from GridViewRow?
in the for-each loop in button click event I need CommandArgument
example code:
foreach (GridViewRow row in MyGridView.Rows)
{
...
string commandArgument = ?;
...
}
According to your comments I understood your mission . You can solve this
by creating Hidden Field for getting Id of table and you can access this id when the checkbox is checked. Then do update on the basis of id. Here I am updating
name column of grid view.
Sample:
WebForm1.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:TemplateField HeaderText="name">
<ItemTemplate>
<asp:Label ID="lblUpdate" runat="server" Text= '<%#Eval("name") %>'></asp:Label>
<asp:CheckBox ID="chkbox" runat="server" />
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
WebForm1.aspx.cs
protected void btnSave_Click(object sender, EventArgs e) {
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType==DataControlRowType.DataRow)
{
CheckBox chkbox = (CheckBox)row.Cells[0].FindControl("chkbox");
HiddenField hdID = (HiddenField)row.Cells[0].FindControl("id");
Label lbl = (Label)row.Cells[0].FindControl("lblUpdate");
if (chkbox!=null)
{
if(chkbox.Checked)
{
string Id = hdID.Value;
//now update name... here by the help of this RowId===> Id
}
}
}
}
Note here Cells[0] means first TemplateField data. And I have used this because I have placed all name field and checkbox field in first templatefield.
I think this will help you. :)
Related
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" CssClass="outdata">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-CssClass="profiledata" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" style="width: 50px !important;" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" OnCheckedChanged="chkSelect_CheckedChanged" runat="server" />
<asp:HiddenField runat="server" ID="hdnAssid" Value='<%# Eval("Asset_ID") %>' />
</ItemTemplate>
<ItemStyle Width="5px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Stop" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlGrdStops"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Suppose I have 2 columns in Gridview.
1. CheckBox
2. DropDownList
What Should be the code in the OnCheckedChange event of checkbox that whenever i check it the dropdownlist of the same row should be filled.
I tried RowDataBound event of gridview but the data is too large,so its take a long time in processing and it unnecessarily checks every rows checkbox.
Plase help since I am new.
Thanks in advance. :)
You can use the NamingContainer of the CheckBox to locate the DropDownList in the same row. PS set AutoPostBack to true on the CheckBox.
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
//cast the sender back to a checkbox
CheckBox cb = sender as CheckBox;
//get the current gridviewrow from the checkbox namingcontainer
GridViewRow row = cb.NamingContainer as GridViewRow;
//use findcontrol to locate the dropdownlist in that row
DropDownList ddl = row.FindControl("ddlGrdStops") as DropDownList;
//add the items to the dropdownlist
ddl.Items.Add(new ListItem() { Text = "DropDownList found", Value = "1" });
}
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.
I am trying to develop an asp c# gridview that has select so that I can display additional details of the record. I also need a check box to allow the user the check the row for further processing. I can achieve each separately but not together. Is it even possible?
Of course it is possible.
For the column of check boxes, use TemplateField column, https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield%28v=vs.110%29.aspx
In data grid, aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" runat="server" />
</ItemTemplate>
</asp:TemplateField>
In code behind:
protected void ButtonProcess_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBoxProcess");
if (chk != null)
{
if (chk.Checked)
{
// This record should be processed
}
}
}
}
The GridView has build in row select functionality, you can enable it by setting AutoGenerateSelectButton property to true:
<asp:GridView ... AutoGenerateSelectButton="true" />
However, it is more user friendly to select the row when user clicks on it (rather than clicking on the link).
To do this, you need to attach a bit of java-script to the row:
void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(sender, "Select$" + e.Row.RowIndex.ToString())
}
Here is also, much better explained solution for row click select:
https://stackoverflow.com/a/6250846/461810
You can use template fields and just add the controls into them.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<select />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<checkbox />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SelectChk" OnCheckedChanged="chk_Click1" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
And in the CS code:
protected void chk_Click1(object sender, EventArgs e)
{
CheckBox MChk = sender as CheckBox;
GridViewRow MyGridR = MChk.NamingContainer as GridViewRow;
GridView1.SelectRow(MyGridR.RowIndex);
}
I have a gridview that loads from a database that has several TemplateFields. How do I retrieve the Eval value from code behind? In other words I need the template field name for that column.
I want to get "Registrations" and store it in a variable.
<asp:TemplateField HeaderText="REG" SortExpression="Registrations">
<EditItemTemplate>
<asp:CheckBox ID="cbRegEdit" runat="server" Checked='<%# (int)Eval("Registrations") == 1 %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReg" runat="server" Enabled="false" Checked='<%# (int)Eval("Registrations") == 1 %>'>
</asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
You have to hook to OnRowDataBound and do something like:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var registrations = ((YourType)e.Row.DataItem).Registrations;
//do something
}
}
Your GridView would then have to be:
<asp:GridView OnRowDataBound="GridView1_RowDataBound" ...
Probably the easiest way is to assign a datakey to your gridview.
An example would be like this:
<asp:Gridview ID="gvExample" runat="server" DataKeyNames="Registrations">
Then in the code behind all you need is the row index and you can do the following:
gvExample.Datakeys(rowindex).value
CheckBox CBreg = (Page.FindControl("cbReg") as CheckBox);
bool Reg = CBreg.Checked; //Reg value stored
You may need to change Page.FindControl to your TemplateField control ID if you cannot find the control this way.
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.