data not showing in modal from gridview - c#

my data is not showing after clicking the Edit button from the Gridview.
here is my GridView code
<asp:UpdatePanel ID ="panel1" runat="server">
<ContentTemplate>
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" AllowPaging="true" OnRowCommand="gv1_RowCommand" CellPadding="4" HeaderStyle-BackColor="CornflowerBlue" BorderWidth="5" BorderColor="CornflowerBlue" Width="100%" CssClass="table table-hover">
<Columns>
<asp:TemplateField HeaderText ="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind ("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Type">
<ItemTemplate>
<asp:Label ID="lbltype" runat="server" Text='<%#Bind ("ItemType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Model">
<ItemTemplate>
<asp:Label ID="lblModel" runat="server" Text='<%#Bind ("ItemModel") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Quantity">
<ItemTemplate>
<asp:Label ID="lblQuan" runat="server" Text='<%#Bind ("ItemQuantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Unit">
<ItemTemplate>
<asp:Label ID="lblUnit" runat="server" Text='<%#Bind ("ItemUnit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Target Date">
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%#Bind ("ItemDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#Bind ("ItemDesc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Remarks">
<ItemTemplate>
<asp:Label ID="lblRem" runat="server" Text='<%#Bind ("ItemRemarks") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="editRecord" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Edit" HeaderText="Edit">
<ControlStyle CssClass="btn btn-info" />
</asp:ButtonField>
<%--<asp:TemplateField HeaderText ="Status">
<ItemTemplate>
<asp:Label ID="lblStat" runat="server" Text='<%#Bind ("ItemStatus") %>'></asp:Label>
<asp:DropDownList ID ="ddlStat" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
and here is my code for .cs
int index = Convert.ToInt32(e.CommandArgument);
//if(e.CommandName.Equals("editRecord"))
//{
GridViewRow gvrow = gv1.Rows[index];
lblIDs.Text = HttpUtility.HtmlDecode(gvrow.Cells[0].Text).ToString() ;
lblitemTypes.Text = HttpUtility.HtmlDecode(gvrow.Cells[1].Text).ToString();
lblModels.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text).ToString();
lblQuans.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text).ToString();
lblUnits.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text).ToString();
lblDates.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text).ToString();
lblDescs.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text).ToString();
lblRemarkss.Text = HttpUtility.HtmlDecode(gvrow.Cells[7].Text).ToString();
//ddlStat.Text = HttpUtility.HtmlDecode(gvrow.Cells[8].Text).ToString();
lblResult.Visible = false;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#editModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditModalScript", sb.ToString(), false);
the page goes through but it doesnt show the data from the gridview, i tried to put a breakpoint and i see that it doesnt have anyvalue inside, what is my error? is the HttpUtility.HtmlDecode correct? how can i transfer the data to the modal for editing. thank you!

When you have an UpdatePanel warp your code and your code not work after a post back you need to do two thinks to find the issue.
Temporary Remove the UpdatePanel and repeat what you do and see if the problem is on your code behind.
place back the UpdatePanel and open the javascript console of your browser and check for javascript errors.

Related

Insert Grid View column value into Textbox and dropdown on button control

I want to Fill gridview column value into given control
something like Project Title value fill inside project Title text box Problem ID fill inside Selected Problem Dropdown and so on... on button click even
i have taken as control name
Project title as txtProjectTitle,
selectProblem Id as ddlSelectProblem,
Project_Start_Date as txtProjectStartDate,
Project_Target_Date as TextBox1,
gridview as GrdTemp,
Procedd button as Button2_Click
ASPX CODE:
[![<asp:GridView ID="GrdTemp" runat="server" Style="width: 100%; text-align: center" class="table table-striped table-bordered" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="S.No." HeaderStyle-Width="5%">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("ID") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Title">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Title") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem ID">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Problem") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Start Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Start_Date") %>' ID="lblID</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Target Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Target_Date") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns> </asp:GridView>][2]][2]
C# code:
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow row = (sender as Label).NamingContainer as GridViewRow;
TextBox txtProject = row.FindControl("txtProjectTitle") as TextBox;
txtProject.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Title"]);
DropDownList ddlProblem = row.FindControl("ddlSelectProblem") as DropDownList;
ddlSelectProblem.SelectedItem.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Problem"]);
txtProjectStartDate.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Start_Date"]);
TextBox1.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Target_Date"]);
}

Maintain ViewState of Checkbox checked on paging in asp.net

I have a Gridview with some data. In that I have 5 rows of paging. Whenever I check on checkbox in first page and go to second page and again I come to first page. The checkbox check value gets disappear.
The value of checked is not retained. How to get it maintain the viewstate of checkbox. Please suggest
CODE:
<asp:GridView ID="grdDisplayCMMData" runat="server" AutoGenerateColumns="false" Width="100%" ShowHeaderWhenEmpty="true" CssClass="heavyTable table" EmptyDataText="No records to display"
AllowPaging="true" PageSize="2" OnPageIndexChanging="grdDisplayCMMData_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID_CMM" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SAP ID">
<ItemTemplate>
<asp:Label ID="lblSAP_ID_CMM" runat="server" Text='<%#Eval("SAP_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID OD CHANGE">
<ItemTemplate>
<asp:Label ID="lblID_OD_COUNTCHANGE_CMM" runat="server" Text='<%#Eval("ID_OD_COUNTCHANGE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID OD CHANGE DATE">
<ItemTemplate>
<asp:Label ID="lblID_OD_CHANGEDDATE_CMM" runat="server" Text='<%#Eval("ID_OD_CHANGEDDATE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RRH COUNT CHANGE">
<ItemTemplate>
<asp:Label ID="lblRRH_COUNTCHANGE_CMM" runat="server" Text='<%#Eval("RRH_COUNTCHANGE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RRH COUNT CHANGE DATE">
<ItemTemplate>
<asp:Label ID="lblRRH_CHANGEDDATE_CMM" runat="server" Text='<%#Eval("RRH_CHANGEDDATE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TENANCY COUNT CHANGE">
<ItemTemplate>
<asp:Label ID="lblTENANCY_COUNTCHANGE_CMM" runat="server" Text='<%#Eval("TENANCY_COUNTCHANGE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TENANCY COUNT CHANGE DATE">
<ItemTemplate>
<asp:Label ID="lblTENANCY_CHANGEDDATE_CMM" runat="server" Text='<%#Eval("TENANCY_CHANGEDDATE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="STATUS">
<ItemTemplate>
<asp:Label ID="lblSTATUS_CMM" runat="server" Text='<%#Eval("STATUS") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CREATED BY" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCREATEDBY_CMM" runat="server" Text='<%#Eval("CREATED_BY") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approve/Reject">
<ItemTemplate>
<asp:CheckBox ID="chkApprRejCMM" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
SERVER CODE
protected void grdDisplayCMMData_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
BindCMMData();
grdDisplayCMMData.PageIndex = e.NewPageIndex;
grdDisplayCMMData.DataBind();
}
catch (Exception ex)
{
string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
}
}
Let me know if anything else is required
Microsoft provided example here.
check list is stored in view state as List.
To transfer data between pages you cannot use viewstate.
The options of transferring data between pages are Session storage, transferring via query string or storing the needed value into some kind of database.
Example for sessions storage at the most basic level:
On first page:
Session["CheckboxValue"] = chkSomeCheckbox.Checked;
On the second page:
bool isCheckboxChecked = Convert.ToBoolean(Session["CheckboxValue"])

Get text box value from grid view Header

I have grid with text box for filter data on header.I have button outside the grid.I am using this gridview for filtering the grid by some columns. When I click on button I want to get value from text box and dropdownlist on codebehind.cs, below is my webform.aspx code of gridview,
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:GridView ID="TrackerGrid" runat="server" BackColor="#CCCCCC" AllowPaging="True" AutoGenerateColumns="false">
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="User ID" SortExpression="User ID">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Eval("User ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<HeaderTemplate>
Full Name:
<asp:DropDownList ID="ddlfullName" runat="server" AutoPostBack="true" OnSelectedIndexChanged="onselectDropdown">
<asp:ListItem Text="ALL" Value="ALL" Selected="True"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("Full Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<HeaderTemplate>
Email Id:
<asp:TextBox ID="txtemail" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<HeaderTemplate>
<asp:Label ID="lbllng" runat="server" Text="Longitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllongi" runat="server" Text='<%# Eval("Longitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lattitude">
<HeaderTemplate>
<asp:Label ID="lbllat" runat="server" Text="Lattitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllatti" runat="server" Text='<%# Eval("Lattitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activated On">
<HeaderTemplate>
<asp:Label ID="lbldevices" runat="server" Text="Activated On"></asp:Label></br>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbldevice" runat="server" Text='<%# Eval("Activated On") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location DateTime" SortExpression="Location DateTime">
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Location DateTime"></asp:Label></br>
<asp:Label ID="lblStartDate" runat="server" AssociatedControlID="txtStartDate" Text="Start Date"></asp:Label>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarStartDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtStartDate" popupbuttonid="imgPopup1"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup1" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</br>
<asp:Label ID="lblEndDate" runat="server" Text="End Date" AssociatedControlID="txtEndDate"></asp:Label>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarEndDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtEndDate" popupbuttonid="imgPopup2"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup2" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDatetime" runat="server" Text='<%# Eval("Location DateTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am getting texbox value in codebehind code.
protected void getTextBoxValue(object sender, EventArgs e)
{
DropDownList ddlfullname = (TrackerGrid.HeaderRow.FindControl("ddlfullName") as DropDownList);
string selectedValue = ddlfullname.SelectedItem.Text;
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = mobilenumber.Text;
TextBox email = TrackerGrid.HeaderRow.FindControl("txtemail") as TextBox;
string emailid = email.Text;
TextBox staloc = TrackerGrid.HeaderRow.FindControl("txtStartDate") as TextBox;
string startlocatdate = staloc.Text;
TextBox endloc = TrackerGrid.HeaderRow.FindControl("txtEndDate") as TextBox;
string endlocadate = endloc.Text;
}
I am getting empty value when I debugging this code.I think my code is correct but how i am not getting value of textboxes, i don't understand. Please help me for solving my issue.
Thanks in advance.
You probably did not wrap the DataBind() of the Gridview inside an IspostBack check. If you do not then the values will be rested by the DataBind instead of being saved with ViewState.
protected void Page_Load(object sender, EventArgs e)
{
//not here
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
if (IsPostBack == false)
{
//but inside an ispostback check
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
}
}

using checkbox to select and delete row from gridiew datasource = session C# .net

I have been searching on here and other sites for three days for a solution. I need to select one or more rows (using checkbox) and delete selected row(s) from a gridview who's datasource is a session datatable as you will see. Not interested in SQLConnections or LINQ Entities. As a result I am not sure if I need to use e.commandarguments, or how to go about it, but I have tried them with no luck.
Error is visible and clearly commented on CART.ASPX.CS page inside the following method
if (chkRemCart != null && chkRemCart.Checked)
Any assistance would be greatly appreciated and if you require any further coding or explanations to help with a solution, just ask.
Thank you in advance.
CART.ASPX
<asp:GridView ID="gvCart" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" CellPadding="4"
HeaderStyle-CssClass="header" EmptyDataText="You have successfully cleared your Shopping Cart"
OnRowDataBound="gvCart_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Movie Selector">
<ItemTemplate>
<asp:CheckBox ID="chkRemCart" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie ID">
<ItemTemplate>
<asp:Label ID="lblMovieID" runat="server" Text='<%# Eval("MovieId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:Label ID="lblDuration" runat="server" Text='<%# Eval("Duration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Genre">
<ItemTemplate>
<asp:Label ID="lblGenre" runat="server" Text='<%# Eval("Genre") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Label ID="lblRating" runat="server" Text='<%# Eval("Rating") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price","{0:n}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnRem" runat="server" OnClick="RemCart" Text="Remove Selection" CssClass="button" Title="Remove Movies From Cart" />
CART.ASPX.CS
Page_Load calling RefreshPages() method. gvCart displaying all columns and rows of items in Datasource/Session/Datatable
public void RefreshPages()
{
if (Session["SelectedMovies"] != null)
{
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
protected void RemCart(object sender, EventArgs e)
{
// Check session exists
if (Session["selectedMovies"] != null)
{
// Opening / Retreiving DataTable.
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
foreach (GridViewRow row in gvCart.Rows)
{
CheckBox chkRemCart = row.Cells[0].FindControl("chkRemCart") as CheckBox;
if (chkRemCart != null && chkRemCart.Checked)
{
// Error appearing on line below. Scroll right to read.
int MovieId = Convert.ToInt32(gvCart.DataKeys[row.RowIndex].Value); // Error here. //Additional information: Index was out of range. Must be non - negative and less than the size of the collection.
MovieTable.Rows.RemoveAt(row.RowIndex);
//Saving session
Session["selectedMovies"] = MovieTable;
// Updating gvCart
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
}
}
Assign DataKeyNames="PrimaryKey" in gridview like below and check
<asp:GridView ID="gvCart" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" DataKeyNames="MovieId" CellPadding="4"
HeaderStyle-CssClass="header" EmptyDataText="You have successfully cleared your Shopping Cart"
OnRowDataBound="gvCart_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Movie Selector">
<ItemTemplate>
<asp:CheckBox ID="chkRemCart" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie ID">
<ItemTemplate>
<asp:Label ID="lblMovieID" runat="server" Text='<%# Eval("MovieId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:Label ID="lblDuration" runat="server" Text='<%# Eval("Duration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Genre">
<ItemTemplate>
<asp:Label ID="lblGenre" runat="server" Text='<%# Eval("Genre") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Label ID="lblRating" runat="server" Text='<%# Eval("Rating") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price","{0:n}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind:
public void RefreshPages()
{
if (Session["SelectedMovies"] != null)
{
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
protected void RemCart(object sender, EventArgs e)
{
// Check session exists
if (Session["selectedMovies"] != null)
{
// Opening / Retreiving DataTable.
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
foreach (GridViewRow row in gvCart.Rows)
{
CheckBox chkRemCart = row.Cells[0].FindControl("chkRemCart") as CheckBox;
if (chkRemCart != null && chkRemCart.Checked)
{
// Error appearing on line below. Scroll right to read.
int MovieId = Convert.ToInt32(gvCart.DataKeys[row.RowIndex].Value); // Error here. //Additional information: Index was out of range. Must be non - negative and less than the size of the collection.
DataRow[] drs = dt.Select("MovieId = '" + MovieId + "'"); // replace with your criteria as appropriate
if (drs.Length > 0)
{
MovieTable.Rows.Remove(drs[0]);
}
}
}
//Saving session
Session["selectedMovies"] = MovieTable;
// Updating gvCart
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}

How to add Controlls on runtime to a Gridview?

First of all the ASPcode, the problemdescription below.
<asp:GridView ID="GridViewContacts" runat="server" ForeColor="#333333" DataKeyNames="L_ID_CONTACT" AllowPaging="True" AllowSorting="True"
OnPageIndexChanging="GridViewContacts_PageIndexChanging" PageSize="25" AutoGenerateColumns="False" OnRowCommand="GV_Contacts_RowCommand" >
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonEdit" runat="server" CommandArgument="Edit" CommandName="Edit" Text="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonView" runat="server" CommandArgument="View" CommandName="View" Text="View">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="L_Name" runat="server" Text='<%# Eval("L_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Companydetails">
<ItemTemplate>
<asp:Label ID="L_Companydetails" runat="server" Text='<%# Eval("L_Companydetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EMail">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False" HeaderText="ID_CONTACT" >
<ItemTemplate>
<asp:Label Visible="false" ID="L_ID_CONTACT" runat="server" Text='<%# Eval("L_ID_CONTACT") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<%-- //Stylesettings here--%>
</asp:GridView>
Okay, then in the CodeBehind I have a Select from my database, where i select the ID_Contact, the Name, the Companydetails, which can be 1 per Row only.
On the RowCreated event I get the UserID of the actual User, and I select all E-Mails the user has, can be 0-10 per row.
Now my problem is:
How can i insert Linkbuttons with the onClick-event in the description into this part of my code?
Like this:
<asp:TemplateField HeaderText="EMail">
<ItemTemplate>
<asp:LinkButton[i] runat="server" onClick="SendEmail">
</asp:Linkbutton[i]>
<asp:LinkButton[i] runat="server" onClick="SendEmail">
</asp:Linkbutton[i]>
</ItemTemplate>
</asp:TemplateField>
So i want to add those controlls with code into THIS TemplateField.
Is this possible ?
Thoughts i allready had:
This.GridViewContacs.Controlls.AddAt(index,Linkbutton)
But also no clue here how it should work.
Thanks in advance,
me
Easiest is to add a placeholder control to the ItemTemplate, as ItemTemplate has no ID.
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="emails" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
and then in RowDataBound event
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder emails = e.Row.FindControl("emails") as PlaceHolder;
if (emails != null)
{
LinkButton lbEmail = new LinkButton();
lbEmail.Text = "your text";
lbEmail.Click += new EventHandler(SendEmail);
emails.Controls.Add(lbEmail);
}
}
Of course, the example is simplified. You can easily extend it to your needs.

Categories