Hi I need help implementing a logic using Gridview control in c#.
I have a gridview and it has many rows. Each row has a Button to click for the user. On each button click i am updating the selected record in the database. Now once row is updated, I need to hide that button to prevent reaction just for that particular row.
1. If i use this
<asp:CommandField ShowEditButton="True" EditText="select" />
, I can't make this hide.
2. If I use this
<asp:TemplateField HeaderText="Your Action">
<ItemTemplate>
<asp:Button
ID="btnAccept"
runat="server"
Text="Accept"
OnClientClick="return confirm('Are you sure you want to Accept this offer?');"
onclick="btnAccept_Click" />
</ItemTemplate>
</asp:TemplateField>
, I can't get the selected row index.
I hope i have cleared what i wanna ask. Thanks in advance.
Use Button control's CommandArgument property specify the row user clicked :
<asp:TemplateField HeaderText="Your Action">
<ItemTemplate>
<asp:Button
ID="btnAccept"
runat="server"
Text="Accept"
OnClientClick="return confirm('Are you sure you want to Accept this offer?');"
CommandName="Accept"
CommandArgument='<%# Eval("RowId") %>'
onclick="btnAccept_Click" />
</ItemTemplate>
</asp:TemplateField>
At code behind :
void btnAccept_Click(Object sender, CommandEventArgs e)
{
if (e.CommandName == "Accept")
{
string rowId = e.CommandArgument;
}
}
Continuing on Canavars solution for 1):
void btnAccept_Click(Object sender, CommandEventArgs e)
{
if (e.CommandName == "Accept")
{
string rowId = e.CommandArgument;
((Button)sender).Visible = false;
}
}
Related
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 have a Gridview control and I have placed a RadioButton in the itemtemplate. When I click a button I'm trying to get the checked property of the radio button. But When I click the checked property is always returning false. Please look into the below code and let me know where I'm making mistake.
aspx Code
<asp:GridView ID="gvDepartments" runat="server" AutoGenerateColumns="False" GridLines="None"AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rdbtn" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lbl" runat="server"></asp:Label>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="btn_Click" CssClass="button small"/>
Code Behind on button click
foreach (GridViewRow row in gvDepartments.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
RadioButton rd = (RadioButton)row.FindControl("rdbtn");
lbl.Text += rd.Checked.ToString();// +rd1.Checked.ToString();
}
}
Result will be False always in the label always. I'm using Ajaxcontroltoolkit in the application, Above controls are present in the update panel and I even tried to placing button and event in the triggers but the result is same. Please help.
Regards,
Nuthan A R
When do you assign and load the DataSource of the GridView? Note that you should do that only if(!IsPostBack) and not on every postback. So use the Page.IsPostBack property.
So assuming that you're using Page_Load for this:
protected void Page_Load(Object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindGridView(); // method that assigns DataSource and calls DataBind
}
}
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 have in my grid a ImageButton in each rows. When i click on it, i need to retrieve the ID of the selected row.
My grid is fulfilled using an ObjectDataSource.
This is the column i'm talking about:
<telerik:GridTemplateColumn UniqueName="ImageColumnDetails">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDetails" runat="server" ImageUrl="~/img/cle-outil_white.gif"
ToolTip="Détails du ticket"
OnClientClick='<%# Eval("idAgir","openRadWin({0})") %>;return false;'/>
</ItemTemplate>
</telerik:GridTemplateColumn>
As you see, i need to specify the IdAgir in my aspx page to pass it by URL to a JS function.
Thank you for your help
Make sure to include idAgir in your DataSource, going with the implementation you're attempting this should work:
<telerik:GridTemplateColumn UniqueName="ImageColumnDetails">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDetails" runat="server" ImageUrl="~/img/cle-outil_white.gif"
ToolTip="Détails du ticket"
OnClientClick='<%# String.Format("openRadWin({0});return false;",DataBinder.Eval(Container,"DataItem.idAgir"))%> '/>
</ItemTemplate>
</telerik:GridTemplateColumn>
-
I personally usually use this approach, and modify my columns on the server side, but I don't really see the difference.
<telerik:GridTemplateColumn HeaderText="User Name" UniqueName="UserName" SortExpression="UserName">
<ItemTemplate>
<asp:HyperLink ID="UserNameLink" runat="server" CssClass="lnkAction icon_toolbar_edit_blue"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>
protected void radGrid_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
var dataBoundItem = e.Item as GridDataItem;
HyperLink userNameLink = (HyperLink)dataBoundItem.FindControl("UserNameLink");
userNameLink.Attributes["href"] = "#";
userNameLink.Attributes["onclick"] = String.Format("selectRow('{0}');return ShowEditUser('{1}');", dataBoundItem.ItemIndex, dataBoundItem.OwnerTableView.DataKeyValues[dataBoundItem.ItemIndex]["id"]);
userNameLink.Text = dataBoundItem.OwnerTableView.DataKeyValues[dataBoundItem.ItemIndex]["UserName"].ToString();
}
}
Hi I have a grid view with a textbox in each row that im trying to get the value of in the RowCommand event. The below code works fine for all rows expect the first one. The textbox.text value for the first row in always empty.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_OnRowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
Title <%# Eval("Title")%>
<asp:TextBox ID="TextBoxAddPost" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("postId") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
bindGridView();
}
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddPost")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox textBox = (TextBox)row.FindControl("TextBoxAddPost");
//Empty for first row but works for all others
Debug.WriteLine("row: " + row.RowIndex + ", textBox:" + textBox.Text.Trim());
GridView1.DataBind();
}
}
The above code has been simplified for illustration purposes. Each row actually contains a child gridview, hence why in need the text box in each row. I fear that the binding in the page_load is overwriting the value of the text box, however, without the page_load binding, the rowCommand Event is not fired.
I find i a bit strange the it works fine for all rows except the first.
For getting data from textbox, You have to set text property first by putting below code.
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>
It will definitely give value from textbox.
Either way, You can also set datakeynames property of gridview.Click here for datakeynames
I tried this and it works fine,GridView1_OnRowCommand fires by clicking on LinkButtonAddPost:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("ID") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and change your page_load event like this:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = Data.RequestPaymentDB.GetRequestPaymentByRequestID(9208060001);
GridView1.DataBind();
}
compare your code with mine.