Within my load method of my page i want to set the Textbox in a templatefield to a value.
Here is my current source code showing my template field textbox item 'txtQuan':
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTotalRate" Text="Qty:" runat="server" />
<asp:TextBox ID="txtQuan" Height="15" Width="30" runat="server" />
<asp:Button ID="addButton" CommandName="cmdUpdate" Text="Update Qty" OnClick="addItemsToCart_Click" runat="server" />
</ItemTemplate>
</asp:TemplateField>
And this is how im trying to set the TextBox value:
string cartQty = Qty.ToString();
((TextBox)(FindControl("txtQuan"))).Text = cartQty;
Im currently receiving a 'nullRefernceException error'.
Use the RowDataBound event to do that. You can look that up on the internet. The arguments to that event handler gives you easy access to each row. You can also loop through the rows using var rows = myGridView.Rows
var rows = myGridView.Rows;
foreach(GridViewRow row in rows)
{
TextBox t = (TextBox) row.FindControl("txtQuan");
t.Text = "Some Value";
}
For the event: GridView RowDataBound
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t = (TextBox) e.Row.FindControl("txtQuan");
t.Text = "Some Value";
}
}
((TextBox)grdviewId.Row.FindControl("txtQuan")).Text=cartQty;
Related
I have a nested GridView(GvMP_Summary_Items). Each row contains a DropDownList. The DropDownList is bounded on the RowDataBound event of the nested GridView.
Each row also contains 1 Button. Upon pressing this button on the RowCommand event, I would like to find the current selected value of the DropDownList so I can use it further on in the code.
The code I have will only get the default value of the DropDownList on each row, which is currently set at 0 for each row.
Below is the RowCommand Event:
Protected Sub GvMP_Summary_Items_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim lb As ImageButton = CType(e.CommandSource, ImageButton)
Dim gvRow As GridViewRow = lb.BindingContainer //Getting current row to get index
Dim GvMP_Summary_Items As GridView = CType(gvRow.FindControl("GvMP_Summary_Items"), GridView)
Dim intMPItem_Qty As Integer = CType(gvRow.FindControl("cboMPItem_Qty"), DropDownList).SelectedValue
Dim strMPItem_Qty As String = CType(gvRow.FindControl("txtMPItem_Qty"), TextBox).Text
End Sub
I have even included a TextBox in the GridView row which default value is empty "". Although on the row if something is entered the on RowCommand event brings back the value with a comma(,) in front of it.
This proves that I am picking up the correct row and can retrieve a value from a TextBox but not a DropDownList.
Is there something I am missing? Why can I return a value entered in a TextBox but not the selected value of a DropDownList? Also why the comma(,) in front of the TextBox value?
Note: In above case code has been written using VB so answers in VB over C# but I can accept both.
This can be done very easily by casting the CommandSource of the RowCommand back to a button and then get the correct row from that. Once you have the row you can use FindControl to locate the DropDownList. This works on every level of nested items and also on the top Control.
VB
Protected Sub GMP_Summary_Items_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
'cast the commandsource back to a button
Dim btn As Button = CType(e.CommandSource,Button)
'get the current gridviewrow from the button namingcontainer
Dim row As GridViewRow = CType(btn.NamingContainer,GridViewRow)
'use findcontrol to locate the dropdownlist in that row
Dim ddl As DropDownList = CType(row.FindControl("cboMPItem_Qty"),DropDownList)
'show the selected value of the dropdownlist
Label1.Text = ddl.SelectedValue
End Sub
Code was translated from C# with a code translator, so it may not be 100% accurate.
C#
protected void GMP_Summary_Items_RowCommand(object sender, GridViewCommandEventArgs e)
{
//cast the commandsource back to a button
Button btn = e.CommandSource as Button;
//get the current gridviewrow from the button namingcontainer
GridViewRow row = btn.NamingContainer as GridViewRow;
//use findcontrol to locate the dropdownlist in that row
DropDownList ddl = row.FindControl("cboMPItem_Qty") as DropDownList;
//show the selected value of the dropdownlist
Label1.Text = ddl.SelectedValue;
}
You do need to bind data to the GridView and the DropDownLists in an
IsPostBack check, otherwise the data will be rebound to the DDL on every PostBack and the selected value is lost
Important things:
Bind parent GridView in Page_Load method
Bind child GridView in parent GridView 's RowDataBound event
Bind DropDownList in child GridView 's RowDataBound event
Add CommandName to the Button which is inside child GridView
Finally, in RowCommand event of child GridView
Get child GridView 's row
Then find all controls inside child GridView from child GridView 's row
I'm not so aware of VB.NET so I have added an example (C#) of Nested GridView with RowCommand event (hope OP can use it in VB.NET):
HTML code (.Aspx):
<form id="form1" runat="server">
<asp:GridView ID="GridView_Outer" OnRowDataBound="GridView_Outer_RowDataBound" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Outer Column1">
<ItemTemplate>
<asp:Label ID="Label_Outer" runat="server" Text='<%# Eval("Label_Outer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Outer Column2">
<ItemTemplate>
<asp:GridView ID="GridView_Inner" OnRowDataBound="GridView_Inner_RowDataBound" OnRowCommand="GridView_Inner_RowCommand" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Inner Column1">
<ItemTemplate>
<asp:Label ID="Label_Inner" runat="server" Text='<%# Eval("Label_Inner") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inner Column2">
<ItemTemplate>
<asp:TextBox ID="TextBox_Inner" Text='<%# Eval("TextBox_Inner") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inner Column3">
<ItemTemplate>
<asp:DropDownList ID="DropDownList_Inner" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inner Column4">
<ItemTemplate>
<asp:Button ID="Button_Inner" runat="server" CommandName="BtnInnerCmd" Text="Inner Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="Label_Result" runat="server"></asp:Label>
</form>
Code-Behind (.Aspx.cs):
DataTable TempDT = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
CreateDataTable();
if (!IsPostBack)
{
GridView_Outer.DataSource = TempDT;
GridView_Outer.DataBind();
}
}
// create DataTable
public void CreateDataTable()
{
TempDT = new DataTable();
TempDT.Columns.Add("Label_Outer");
TempDT.Columns.Add("Label_Inner");
TempDT.Columns.Add("TextBox_Inner");
TempDT.Rows.Add("OuterLabel", "InnerLabel", "");
TempDT.Rows.Add("OuterLabel", "InnerLabel", "");
// store DataTable into ViewState to prevent data loss on PostBack
ViewState["DT"] = TempDT;
}
// Calls Outer GridView on Data Binding
protected void GridView_Outer_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if gridview row is not in edit mode
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get Outer GrridView 's controls
Label Label_Outer = (Label)e.Row.FindControl("Label_Outer");
GridView GridView_Inner = (GridView)e.Row.FindControl("GridView_Inner");
// get DataTable from ViewState and set to Inner GridView
GridView_Inner.DataSource = (DataTable)ViewState["DT"];
GridView_Inner.DataBind();
}
}
// Calls Inner GridView on Data Binding
protected void GridView_Inner_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if gridview row is not in edit mode
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get Outer GrridView 's controls
DropDownList DropDownList_Inner = (DropDownList)e.Row.FindControl("DropDownList_Inner");
// Create a DataTable to Bind data for DropDownlist
DataTable TempDDLDT = new DataTable();
TempDDLDT.Columns.Add("ItemText");
TempDDLDT.Columns.Add("ItemValue");
TempDDLDT.Rows.Add("ItemText1", "ItemValue1");
TempDDLDT.Rows.Add("ItemText2", "ItemValue2");
// bind DataTable to the DropDownList
DropDownList_Inner.DataSource = TempDDLDT;
DropDownList_Inner.DataTextField = "ItemText";
DropDownList_Inner.DataValueField = "ItemValue";
DropDownList_Inner.DataBind();
}
}
// Calls when Inner GridView 's button clicked
protected void GridView_Inner_RowCommand(object sender, GridViewCommandEventArgs e)
{
// get Inner GridView 's clicked row
GridViewRow InnerGridViewRow = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
// get Inner GridView 's controls from clicked row
TextBox TextBox_Inner = (TextBox)InnerGridViewRow.FindControl("TextBox_Inner");
DropDownList DropDownList_Inner = (DropDownList)InnerGridViewRow.FindControl("DropDownList_Inner");
// check if correct button is clicked
if (e.CommandName == "BtnInnerCmd")
{
string DropDownListValue = DropDownList_Inner.SelectedValue;
string TextBoxValue = TextBox_Inner.Text;
Label_Result.Text = "DropDownList 's Selected Value is " + DropDownListValue +
"<br />TextBox 's Entered Value is " + TextBoxValue;
}
}
Demo Image:
Note: Above DropDownList selects Selected Value not Text.
I have written code like below lines of code
protected void grdView_DataBinding(object sender, EventArgs e)
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, LicenseType);
foreach (GridViewRow row in grdView.Rows)
{
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
TextBox txtDateIssued = row.FindControl("txtEffectiveDate") as TextBox;
TextBox txtDateExpiration = row.FindControl("txtExpirationDate") as TextBox;
TextBox txtLicenseNumber = row.FindControl("txtLicenseNumber") as TextBox;
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
txtLicenseNumber.Text = lds.Tables[0].Rows[i]["LicenceNumber"].ToString();
}
}
}
I want to bind grid view without using datasource property of gridview. The above code is not working...
Let's Suppose lds contains data like
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Similarily Grid will also contain the data
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Here is grid view's design
<asp:GridView ID="grdView" AutoGenerateColumns="false" OnDataBinding="grdView_DataBinding" BorderWidth="0" runat="server" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" style="padding:12px 5px;" runat="server" />
<br />
<asp:RequiredFieldValidator ID="ValReqLN" Display="Dynamic" runat="server"
ErrorMessage="License Number cannot be Blank." ControlToValidate="txtEffectiveDate"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:TextBox ID="txtEffectiveDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help!!!
Why would you not use datasource property ? you said: "i want to bind gridview programically because I have to give many conditions inside gridview's rows according to business logic in order to display data in the gridview.
Here is how you can do that:
Code behind:
protected void grdView_DataBinding(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["txtLicenseNumber"].ToString().ToLower() == "abc")
{
//Apply business logic here on each row, hide/show etc
e.Row.CssClass = "highlighted";
}
}
}
Read more here on:
Dynamically change GridView Cell value using RowDataBound event in ASP.Net using C# and VB.Net
Selectively apply css to a row in a gridview
I want to change the text/value of a cell in certain condition in GridView. I have a cell that return 'P', 'A', 'R' when I bind the Gridview from database. I want to show 'Pending' in case of 'P', 'Approved' in case of 'A' and 'Rejected' in case of 'R' in the dropdown with the update button. I want to change the status of a record.
How can I change the text AND do my required task at the time of Binding of data.
<asp:TemplateColumn>
<HeaderStyle CssClass="bgB white p5 b treb ttu w10" />
<HeaderTemplate>
<asp:Label ID="lblstatus" runat="server" Text="Status"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblrmastatus" runat="server" Text='<%# Bind("RMA_STATUS") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
A way to solve this is to handle the RowDataBound event. It is raised once per row (also header and footer rows, so you need to filter for rows of type DataRow). You can use it to adjust the data that are displayed or the way they are displayed. Also you can set the values of a DropDown in the event. See the link for a sample.
In order to add the DropDown-column to the GridView, use a TemplateColumn and put the DropDown into the ItemTemplate. Access the corresponding cell in the RowDataBound event handler. Use the FindControl method to retrieve the DropDown control and set its values.
The following sample shows how to set the Label and the DropDownList programmatically:
GridView
The GridView shows both the original status and a new status with the long text, a DropDownList and a command column to update the data.
<asp:GridView ID="gdv" runat="server"
OnRowDataBound="gdv_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RMAStatus" HeaderText="Original RMA Status" />
<asp:TemplateField HeaderText="Adjusted RMA Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
Code-behind
In Code-behind, I've defined a class called DataClass that contains the data (you can also use a DataTable, but for the sample it was easier to use a class to generate some data). Also, a dictionary contains the mappings from the short status to the long text.
In Page_Load, the dictionary is set up and if it is no PostBack, the data are bound.
Finally, in gdv_RowDataBound, the label is set for each row and the DropDownList is initialized. Please note that the Label and the DropDownList for the row are retrieved by using FindControl.
public class DataClass
{
public string RMAStatus { get; set; }
}
private readonly Dictionary<string, string> rmaStatusMappings = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
rmaStatusMappings.Add("R", "Rejected");
rmaStatusMappings.Add("A", "Approved");
rmaStatusMappings.Add("P", "Pending");
if (!IsPostBack)
{
var data = new DataClass[] {
new DataClass() { RMAStatus = "P" },
new DataClass() { RMAStatus = "A" },
new DataClass() { RMAStatus = "R" },
new DataClass() { RMAStatus = "P" },
};
gdv.DataSource = data;
gdv.DataBind();
}
}
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var rowStatus = ((DataClass)e.Row.DataItem).RMAStatus;
// Set label to long status
var lblStatus = e.Row.Cells[1].FindControl("lblStatus") as Label;
if (lblStatus != null)
lblStatus.Text = rmaStatusMappings[rowStatus];
// Set drop down items
var ddlStatus = e.Row.Cells[2].FindControl("ddlStatus") as DropDownList;
if (ddlStatus != null)
{
ddlStatus.DataTextField = "Value";
ddlStatus.DataValueField = "Key";
ddlStatus.DataSource = rmaStatusMappings;
ddlStatus.DataBind();
ddlStatus.SelectedValue = rowStatus;
}
}
}
Let me know in the comments if you have any questions.
I have a GridView with a TemplateField column that I put PlaceHolder controls in. During the DataBound event for the GridView I dynamically add a few CheckBoxes to the PlaceHolder. That works fine and displays as expected.
My problem is that during the RowUpdating event the PlaceHolder contains no controls; my CheckBoxes are missing. I also noticed that they're missing during the RowEditing event.
I want to be able to get the values of the CheckBoxes during the RowUpdating event so I can save them to the database.
Here's some example code. I've trimmed out a lot to reduce size, but if you want to see specifics just ask and I'll be happy to add more.
HTML:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
ondatabound="gridView_DataBound" onrowupdating="gridView_RowUpdating"
onrowediting="gridView_RowEditing" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
<EditItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="updateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
// This method works fine, no obvious problems here.
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder)row.FindControl("countriesPlaceHolder");
// Create a CheckBox for each country and add it to the PlaceHolder
foreach (Country country in this.Countries)
{
bool isChecked = holidays.ElementAt(i).Countries.Any(item => item.ID == country.ID);
var countryCheckBox = new CheckBox
{
Checked = isChecked,
ID = country.Abbreviation + "CheckBox",
Text = country.Abbreviation
};
placeHolder.Controls.Add(countryCheckBox);
}
}
}
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = gridView.Rows[e.NewEditIndex].FindControl("countriesPlaceHolder").Controls;
gridView.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = ((PlaceHolder)gridView.Rows[e.RowIndex].FindControl("countriesPlaceHolder")).Controls;
// This is where I'd grab the values from the controls, create an entity, and save the entity to the database.
gridView.EditIndex = -1;
BindData();
}
This is the article that I followed for my data binding approach: http://www.aarongoldenthal.com/post/2009/04/19/Manually-Databinding-a-GridView.aspx
You need to call your BindData() method on page load.
"Dynamic controls or columns need to be recreated on every page load, because of the way that controls work. Dynamic controls do not get retained so you have to reload them on every page postback; however, viewstate will be retained for these controls."
See Cells in gridview lose controls on RowUpdating event
Also in the article you linked, there is an ItemTemplate and an EditItemTemplace because they have different displays, i.e. read only and editable. Yours are the same so I think you could simplify your design:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ondatabound="gridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" Text="Edit" onclick="editButton_Click" ></asp:LinkButton>
<asp:LinkButton ID="updateButton" runat="server" Text="Update" onclick="updateButton_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder) row.FindControl("countriesPlaceHolder");
var countryCheckBox = new CheckBox
{
Checked = true,
ID = "auCheckBox",
Text = "Aus",
Enabled = false
};
placeHolder.Controls.Add(countryCheckBox);
var editButton = (LinkButton)row.FindControl("editButton");
editButton.CommandArgument = i.ToString();
var updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.CommandArgument = i.ToString();
updateButton.Visible = false;
}
}
protected void editButton_Click(object sender, EventArgs e)
{
LinkButton editButton = (LinkButton) sender;
int index = Convert.ToInt32(editButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.Visible = true;
editButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
checkbox.Enabled = true;
// Get value and update
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
LinkButton updateButton = (LinkButton)sender;
int index = Convert.ToInt32(updateButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton editButton = (LinkButton)row.FindControl("updateButton");
editButton.Visible = true;
updateButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
// Get value and update
checkbox.Enabled = false;
}
}
If you want to be it enabled from the get go, just remove the enabled checks and you can delete your edit button.
Hope that helps.
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView. I have a regular Button control to which I added some code like this
if (e.CommandName == "addToSession")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
//storing title, author, pictureUrl into session variables to 'carry them over' to RateBook.aspx
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why. I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>' runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Please advise.
Regards,
Arian
I believe you can accomplish your needs with an ImageButton, as it supports all the major Button functionality, including CommandName (see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagebutton.commandname.aspx).
Try this out:
<asp:ImageButton ID="LinkButton1" runat="server"
CommandName="ratedBooks"
ImageUrl='<%#Eval("pictureUrl") %>' />
Also, note that your format exception could be coming from the lines that read:
Convert.ToInt32(e.CommandArgument);
The reason being that there appears from this code snippet to be no value assigned to the CommandArgument of the button. Convert.ToInt32 requires a valid integer value to be passed in, which means that the ImageButton needs to have a number bound to its CommandArgument property.
If you based your solution on this MSDN reference (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx), note that the <asp:ButtonField> column type gets special treatment; the CommandArgument is set to the row index. When you use a template field, ASP.NET requires you to specify or data bind your own command argument.
Update
This question contains details on binding the grid view row index to a custom button:
ASP.NET GridView RowIndex As CommandArgument
A possible solution is to add the ItemDataBound event handler and search for the image button change its image url.
MyGrid.RowDataBound += new RepeaterItemEventHandler(MyGrid_RowDataBound);
void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
ImageButton image = e.Row.FindControl("MY_IMAGE_CONTROL") as ImageButton;
image.ImageUrl = "PATH_TO_IMAGE";
}
}
Hope it helps.
You need CommandArgument
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/Modelos/Img/deleted.gif" />
</ItemTemplate>
</asp:TemplateField>
code behind C#
public void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string t;
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grid1.Rows[index];
t = selectedRow.Cells[2].Text;
}
}
On ASPX
<asp:GridView ID="grid1" runat="server" onselectedindexchanged="GridView1_SelectedIndexChanged" ...