hey I'm using to buttons in a gridview each which I want to assign to specific action involves retrieving certain cell values from the gridview columns
I tried using
GridViewRow row = (GridViewRow (((Button)e.CommandSource).NamingContainer);
but it gives me Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.Button'.
I also tried
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
it gives me the following error
Specified argument was out of the range of valid values.
Parameter name: index
note that when I tried to specify the commandParameters property of the ButtonField the compiler said that it's not a valid parameter for the ButtomField
and I have 8 columns in the gridview so its not out of range
or alternatively could I use more than one select command button
if so how to say which one is clicked??
please help me im desperate
ASP code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="AcitivityId" DataSourceID="SqlDataSource1" Height="304px" Width="912px" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="AcitivityId" HeaderText="AcitivityId" InsertVisible="False" ReadOnly="True" SortExpression="AcitivityId" />
<asp:BoundField DataField="ActiviityName" HeaderText="ActiviityName" SortExpression="ActiviityName" />
<asp:BoundField DataField="ActivityLocation" HeaderText="ActivityLocation" SortExpression="ActivityLocation" />
<asp:BoundField DataField="ActivityStartDate" HeaderText="ActivityStartDate" SortExpression="ActivityStartDate" />
<asp:BoundField DataField="ActivityDueDate" HeaderText="ActivityDueDate" SortExpression="ActivityDueDate" />
<asp:BoundField DataField="ActivityDescription" HeaderText="ActivityDescription" SortExpression="ActivityDescription" />
<asp:ButtonField ButtonType="Button" CommandName="Avaliable" Text="Show avaliable buses" />
<asp:ButtonField ButtonType="Button" CommandName="Assigned" Text="Show assigned buses "/>
</Columns>
</asp:GridView>
I use this code in a number of places on my site to get the row from an object triggering a GridViewRowCommand
protected void btnUpdate_Command(object sender, CommandEventArgs e)
{
GridViewRow g = (GridViewRow)((Button)sender).NamingContainer;
// other stuff
}
Hope this helps.
Related
I have a gridview that is filled when the page is loaded with a dataReader.
I can add a column with hyperlinks but I need the url to contain the GenCod that is dynamically added line by line to the gridView so each link sends to its detail page.
URL Example: http://localhost:50228/misesenventedetail.aspx?GenCod=9788416657544
How can i use the index or name of the column to get the GenCod?
<asp:GridView ID="aParaitre_GridView" runat="server" OnRowCommand="RowCommand" >
<Columns>
<asp:ButtonField buttontype="Image" CommandName="AjouterAuPanier" ImageUrl="~/Images/buy_this_logo.png" />
<asp:HyperLinkField NavigateUrl="url+Parameter+GENCOD" Text="VoirDetail" />
</Columns>
</asp:GridView>
This GridView contains much more columns.
Getting Error: System.Web.UI.WebControls.HyperLinkField has no DataBinding.
With the the following code:
<asp:HyperLinkField
NavigateUrl='<%# String.Format("~/misesenventedetail.aspx?GenCod={0}", Eval("GenCod"))%>'
Text="Detail"
runat="server"
/>
I was hoping something like this would work
<asp:HyperLinkField
id="MyLink"
NavigateUrl="~/misesenventedetail.aspx?GenCod<%= gencod %>"
runat="server" />
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
// Gets the index of the line (row) where we click
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow ligneClick = aParaitre_GridView.Rows[index];
// Gets GenCod from column 1
var GenCod = ligneClick.Cells[1].Text;
MyLink.NavigateUrl = string.Format("../mypage.aspx?id={0}", GenCod );
}
SOLVED
I was able to resolve my problem with this:
<asp:HyperLinkField
DataNavigateUrlFields="GenCod" DataNavigateUrlFormatString="~/misesenventedetail.aspx?GenCod={0}" Text="Voir Details"
runat="server" />
StackOverflow is so great.
I want to change the background color of the Gridview row. The situation is I want to change the background color of that particular row whose BoundField Id is equal to the value displayed in the textbox outside the Gridview. I am able to achieve using RowDataBound and also in !IsPostBack and in page load too, but the problem is the color just flash off (quickly disappear in a fraction of millisecond) and does not stay (unable to hold). I have seen other similar example which is available but it doesn't meet my situation, so please don't mark as duplicate.
Below is my Gridview:
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvCustomers_RowDataBound">
<Columns>
<asp:HyperLinkField HeaderStyle-Width="150px" DataTextField="AssetsName" HeaderText="Product" />
<asp:BoundField HeaderStyle-Width="150px" DataField="InventorySubName" HeaderText="Inventory"
ItemStyle-CssClass="" />
<asp:BoundField HeaderStyle-Width="50px" DataField="Id" HeaderText="Id" Visible="true"
ItemStyle-CssClass="" />
</Columns>
</asp:GridView>
Code behind :
protected void gvProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow row in gvProduct.Rows)
{
if (row.Cells[2].Text.Equals(txt_AId1.Text)) //txt_AId1.Text is retrieved during pageload from url string
{
row.BackColor = System.Drawing.Color.Red;
row.ForeColor = System.Drawing.Color.White;
}
}
}
I'm currently working on an in house project, I've created a GridView connected to a SQL table which looks like this:
GridView1
I created the view content buttons using the following code:
<Columns>
<asp:ButtonField ButtonType="Button" Text="View Content" CommandName="Select" />
<asp:BoundField DataField="ContentID" HeaderText="ContentID" InsertVisible="False" ReadOnly="True" SortExpression="ContentID" />
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="URL" HeaderText="URL" Visible="true" SortExpression="URL" />
</Columns>
But this is where I am now stuck. I would like to click on the view content button and have it navigate to the URL on the selected row.
The URL comes from the SQL Table and there is a string so I'd imagine, it would need to be converted first but I could be wrong.
I started to put my code in the following:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewCommandEventArgs x = (GridViewCommandEventArgs)e;
if (x.CommandName == "Select")
{
GridViewRow row = GridView1.SelectedRow;
}
}
Add your code in GridView1_RowCommand event of gridview:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
int index = row.RowIndex;
string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
Response.Redirect(url); // url can be from your sql table
}
}
Note: Don't forget to add OnRowCommand event in GrindView <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" >
GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
int index = row.RowIndex;
string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
Response.Redirect(url); // url can be from your sql table
So i made the change. Unfortunately, BoundField does not contain a definition for NamingContainer.
Also, GridView1.Rows[index].FindControl("URL") as BoundField fails due to the following error, cannot convert type 'system.web.ui.control' to 'system.web.ui.webcontrols.boundfield' via a reference conversion, boxing conversion, unboxing conversion or null type conversion.
I'm using ASP.net and i've added a delete button on a gridview and im trying to remove the row of the button clicked. The thing is though, that i get an InvalidOperationException on my foreach.
I may have other errors in the code or my logic may be wrong so if you see any of it please point them out. Thanks.
gridView cart.ASPX:
<asp:GridView ID="CartGrid" runat="server" AutoGenerateColumns="false" OnRowDeleting="RemoveSelected">
<Columns>
<asp:BoundField DataField="product_name" HeaderText="Name" />
<asp:BoundField DataField="price_per_unit" HeaderText="Price" />
<asp:BoundField DataField="unit" HeaderText="Unit" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="delSelected" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
delete method cart.ASPX.CS
protected void RemoveBtn(object sender, GridViewDeleteEventArgs e)
{
ArrayList cartList = (ArrayList)Session["cartList"];
GridViewRow row = (GridViewRow)CartGrid.Rows[e.RowIndex];
String name = row.Cells[0].Text;
//String name = (string)CartGrid.DataKeys[e.RowIndex].Value;
//String name = CartGrid.SelectedRow.Cells[1].Text;
foreach (product p in cartList)
{
if (p.product_name.Equals(name))
{
cartList.Remove(p);
}
}
CartGrid.DataBind();
}
Hi I think the issue is that you are using the cartlist for loop and at the same time you want to delete values from the same which is not possible .
just you need to change your approach like create the empty list and add all the index into it from where you have to delete the value Staring from bottom to top like from end of list so that it can not effect the index of the list by deleted value and after loop you can delete it using the new empty list which contain the list of all the values which should be deleted.
You can't modify the collection you're iterating over with the foreach - please see this question for more information.
I have a function in my code-behind that sets a datagrid. I create a new blank column and add it to my datagrid and I want to add a value to the column for only one row that matches an object id. For some reason the cell doesn't store the text I set it to though. Any thoughts?
public void SetContacts(IEnumerable<User> contactList, User reqUser)
{
BoundColumn reqColumn = new BoundColumn();
reqColumn.HeaderText = "";
dgExistingContacts.Columns.Add(reqColumn);
dgExistingContacts.DataSource = contactList;
foreach (DataGridItem row in dgExistingContacts.Items)
{
if (row.Cells[0].Text == reqUser.id.ToString())
row.Cells[6].Text = "Requestor";
}
dgExistingContacts.DataBind();
}
Here's my datagrid if that helps:
<asp:DataGrid runat="server" ID="dgExistingContacts" AutoGenerateColumns="false" CssClass="styledGray" HeaderStyle-CssClass="head" CellSpacing="1" CellPadding="4" GridLines="None" AlternatingItemStyle-CssClass="even" ItemStyle-CssClass="odd">
<Columns>
<asp:BoundColumn DataField="Id" Visible="false" />
<asp:BoundColumn DataField="Title" HeaderText="Role" />
<asp:BoundColumn DataField="LastName" HeaderText="Last Name" ItemStyle-Wrap="false" />
<asp:BoundColumn DataField="FirstName" HeaderText="First Name" ItemStyle-Wrap="false" />
<asp:BoundColumn DataField="Phone" HeaderText="Phone" DataFormatString="{0:(###) ###-####}" />
<asp:BoundColumn DataField="EmailAddress" HeaderText="Email" ItemStyle-Wrap="false" />
</Columns>
</asp:DataGrid>
I feel like it should be simple but I can't figure out why it's not binding.
Try handling the GridView's RowDataBound event and adding the value there.
As I see you are adding a column to dgExistingContacts and then assign contactList as DataSource of dgExistingContacts that means you first add column and then reset DaraGrid to former DataSource in this code:
dgExistingContacts.Columns.Add(reqColumn);
dgExistingContacts.DataSource = contactList;
I think when you assign a DataSource to GridView,any thing that you changed in it will be reseted.so maybe by deleting dgExistingContacts.DataSource = contactList;from codes, your problem will be solved.
I figured out that you have to bind the data before trying to change the contents. I ended up with this:
public void SetContacts(IEnumerable<User> contactList, User reqUser)
{
BoundColumn reqColumn = new BoundColumn();
reqColumn.HeaderText = "";
dgExistingContacts.Columns.Add(reqColumn);
dgExistingContacts.DataSource = contactList;
dgExistingContacts.DataBind();
foreach (DataGridItem row in dgExistingContacts.Items)
{
if (row.Cells[0].Text == reqUser.id.ToString())
row.Cells[6].Text = "Requestor";
}
}