ASP- Get a GridRow value / OnClick method - asp.net

I'm working on a C#/ASP 4.0 project where I'm trying to make a shopping cart application.
There is a GridView on my Products page that shows all of the items, and I want the user to be able to click an "Add to Cart" button field in this GridView which will, obviously, add an item to their cart.
I'm having issues actually setting an OnClick event for the gridview, though? That doesn't seem to be available in the Event menu in the Properties. Additionally, I can't seem to figure out how to get the specific row, either. I have method that does this...
int productID = Convert.ToInt32(GridView1.Rows[n].Cells[0].Text);
AddToCart(productID);
But I have no idea how to figure out n, or how to have this method get called when they click that ButtonField in the gridview.

You could do this:
First, add a template field to the gridview:
<asp:TemplateField HeaderText="Add to Cart">
<ItemTemplate>
<asp:Button id="bthAddToCart"
CommandArgument'<%#Eval("ProductID")%>'
OnClick="bthAddToCart_Click"
Text="Add to Cart"
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
Now, add the handler for the Click event of the button:
protected void bthAddToCart_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int productID = Convert.ToInt32(button.CommandArgument);
AddToCart(productID);
}

You can use the template fields like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Data Found.
</EmptyDataTemplate>
</asp:GridView>
Then on your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}
Hope this helps! Good Luck!

Use the OnRowCommand event of the grid view. More details: here

You have to use OnRowCommand Event for Gridview. Use Following Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
In C# Code use following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add To Cart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}

Related

How to fetch the Value of a LinkButton in a GridView Template Field

I Have a LinkButton In a TemplateField In a GridView. The LinkButton is bound to database which shows the time save in database.All I want is to fetch each linkbutton time value and compare it to current time and if linkbutton time is less than current time ,make it disable.
Any pointers will be helpful.
Thanks in advance.
<asp:GridView ID="grdview" AutoGenerateColumns="false" runat="server" OnRowCommand="grdview_RowCommand">
<Columns>
<asp:BoundField DataField="AudiName" DataFormatString="Audi {0}" HeaderText="Audi Name" />
<asp:TemplateField HeaderText="StartTime">
<ItemTemplate>
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
CommandName="time"
CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
<asp:HiddenField runat="server" ID="hf1" Value='<%#Eval("StartTime")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use the OnRowDataBound event to hook into the data binding and disable the button.
Form
<asp:GridView ID="MyGridView"
OnRowDataBound="MyGridView_RowDataBound"
runat="server">
....
</asp:GridView>
CodeBehind
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the button
var linkButton = (LinkButton) e.Row.FindControl("MyLinkButton");
// Toggle enabled/disabled based on time
// Using the button text is probably a bad idea, but is used here for demonstration purposes
linkButton.Enabled = (Convert.ToDateTime(linkButton.Text) > DateTime.Now);
}
}
The code above has not been tested, but should give you an idea of how you can approach this.
You can set the Enabled property of LinkButton comparing with the current time:
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
Enabled = '<%# ((DateTime)Eval("StartTime")< DateTime.Now )? false : true %>'
CommandName="time" CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>

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.

Gridview under Repeater control in asp.net

i have a repeater control which contains grids, based on values from database, say for example i have 2 grids inside repeater control, now both the grids contains a column which have up and down buttons, now when user clicks on the button from any grids, how can i check from which grid the button is called.
below is my code where i am filling the grids on RepeaterItemDataBound Event
GridView gvw = e.Item.FindControl("grid") as GridView;
gvw.DataSource = info.GetStories(sectionNames[e.Item.ItemIndex].Trim());
gvw.DataBind();
here section name contains the name of the sections, based on number of sections, i generate the grids.
My Design looks like this:
<asp:Repeater ID="rptGrids" runat="server"
OnItemDataBound="rptGrids_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="grid" runat="server" Width="100%" CellPadding="5" AllowPaging="true" ShowHeader="true" PageSize="10" AutoGenerateColumns="false" OnRowCommand="Stories_RowCommand">
<Columns>
<asp:BoundField DataField="ArticleID" HeaderText="Article ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="CategoryID" HeaderText="Category ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="Title" HeaderText = "Article Title" />
<asp:BoundField DataField="PublishDate" DataFormatString="{0:d}" HeaderText="Publish Date" ItemStyle-CssClass="center" />
<asp:TemplateField HeaderText="Select Action" ItemStyle-CssClass="center">
<ItemTemplate>
<asp:ImageButton ID="btnMoveUp" runat="server" ImageUrl="/images/up.gif" CommandArgument="Up" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnMoveDown" runat="server" ImageUrl="/images/dn.gif" CommandArgument="Down" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/deny.gif" CommandArgument="Delete" OnClientClick="return confirm('Are you sure you want to delete this article?');" CommandName='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="hdStoriesSortOrder" runat="server" Value='<%# Eval("SortOrder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="blank"></div>
</ItemTemplate>
</asp:Repeater>
this is my gridviews row_command event
protected void Stories_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandName.Split(',')[0]);
string section = e.CommandName.Split(',')[1].Trim().ToString();
string command = e.CommandArgument.ToString();
if (command.ToLower() == "up")
{
GridView grd = rptGrids.Items[1].FindControl("grid") as GridView; // If i specify the index here, i gets proper grid, but how to recognize at runtime.
Response.Write(grd.Rows.Count);
}
else if (command.ToLower() == "down")
{
}
}
can anyone tell me how can i get from which grid up/down button has been clicked.
You can use command argument to pass required value.
Here is sample of using imagebutton in similar way:
<asp:ImageButton ID="btnView" runat="server" ToolTip="<% $resources:AppResource,Edit %>"
SkinID="EditPage" CommandName="myCommand" CommandArgument='<%# Eval("CustomerId") %>'
PostBackUrl='<%# "~/AdminPages/Customer.aspx?id=" + Eval("CustomerId").ToString() %>' />
Take notice on CommandArgument property.You can set it with value that indicates specific gridview inside repeater.
And here is how to check the value:
protected void EntityGridViewContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
//here you can check for command name...
switch (e.CommandName)
{
case "myCommand":
//here you access command argument...
int customerId = Convert.ToInt32(e.CommandArgument.ToString());
break;
}
//here is how you access source gridview...
GridView gridView = (GridView)sender;
string controlId = gridView.ID;
}
You can also set CommandArgument using this approach:
CommandArgument='<%# GetMySpecialValue() %>'
Then you should declare function on page side something like this:
public string GetMySpecialValue()
{
return "some value";
}

show data in outside textbox from selected row in gridview

I am having a grid view created by using template fields. I inserted a link button using template fields in the grid view.
There are 4 textboxes outside the GridView.. i want to select the row on link button's click and put the selected row's data in text boxes. I am using a row command even for this but its not working ... the syntax i am using is .:
<asp:GridView ID="gview" AutoGenerateColumns="False" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" onrowcommand="gview_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Book Name">
<ItemTemplate>
<%#Eval("book_name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Author">
<ItemTemplate>
<%#Eval("book_author") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Publisher">
<ItemTemplate>
<%#Eval("book_Publisher") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Price">
<ItemTemplate>
<%#Eval("book_Price") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton ID="lnkDet" CommandName="cmdBind" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" runat="server" CausesValidation="false">View Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and Code behind file :
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdBind")
{
LinkButton lb = (LinkButton)e.CommandSource;
int index = Convert.ToInt32(lb.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}
}
Can anyone tell me how to do this.
I think this works:
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "cmdBind")
{
int index = Convert.ToInt32(e.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}}
Attempting it the way you are is not impossible, but it may be easier to just use the in built select buttons for each row. That way you can just use the SelectedIndexChanged event of the gridview:
protected void gview_SelectedIndexChanged(object sender, EventArgs e)
{
txt_name.Text = gview.SelectedRow.Cells[0].Text;
txt_author.Text = gview.SelectedRow.Cells[1].Text;
txt_price.Text = gview.SelectedRow.Cells[2].Text;
}

ASP.NET Grid View Problem

I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >

Resources