Get the element from itemTemplate in gridview asp.net - c#

I want to ask a question, I'm actually looking for a way to modify the status of a textbox in my gridview, I'm quite lost since I just started this language a few weeks ago and i can't find a satisfying answer (maybe I apply them the wrong way maybe you will be able to help me there. Here is my code :
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="centrer">
<asp:Image ID="IMG_attente" runat="server" ImageUrl="~/Images/1px.gif" Height="32px" />
</div>
<asp:Panel ID="panListes" runat="server" Visible="false" CssClass="formulaire">
<asp:Label runat="server" ID="LabelErreur" Visible="false"></asp:Label>
<asp:GridView ID="ListePieceFlash" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceListePieceFlash"
OnRowEditing="ListePieceFlash_RowEditing" OnRowCancelingEdit="ListePieceFlash_RowCancelingEdit"
EnableModelValidation="True" SkinID="Source_DarkBlue" AllowPaging="True" DataKeyNames="NumOF"
OnRowCommand="ListePieceFlash_RowCommand" Width="100%" AllowSorting="True">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/Images/annuler.gif" CommandName="cancel"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Annuler" />
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/okvert.gif" CommandName="save"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Sauvegarder" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/Images/edit.png" CommandName="edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Sélectionner" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="NumSerieLabel" runat="server" Text="NumSerie"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="NumSerie" runat="server" OnTextChanged="OnNumSerieChanged" /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="SymboleLabel" runat="server" Text="Symbole"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="Symbole" runat="server" Enabled="False" OnTextChanged="OnSymboleChanged" /></ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceListePieceFlash" runat="server" ConnectionString="<%$ ConnectionStrings:PRMConnectionString %>"
SelectCommand="exec [dbo].[getListePieceFlash]"></asp:SqlDataSource>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
As you can see my "Symbole" TextBox is disabled at start but I want it to be enabled when i fill the first one and there is more than one element, here is the code behind (the SQL part is a stored procedure):
protected void OnNumSerieChanged(object sender, EventArgs e)
{
numSerieValue = (sender as TextBox).Text;
var con = Sql.Instance.ObtenirConnexionSql();
SqlCommand cmd = ObtenirCommande(con);
cmd.CommandText = "dbo.getListPiece";
Int32 count = (Int32)cmd.ExecuteScalar();
if (count > 1)
(ListePieceFlash.FindControl("Symbole") as TextBox).Enabled = true;
}
The problem is on the last line and I don't really know how to get over it actually, can someone help me? Thank you very much :)

ListePieceFlash.FindControl("Symbole") returns null because you cannot find the TextBox via GridView.FindControl. The NamingContainer of the TextBox is the GridViewRow.
You get it by casting the Sender in OnNumSerieChanged to TextBox and it's NamingContainer property to GridViewRow. Then use row.FindControl("Symbole") to find the target TextBox:
protected void OnNumSerieChanged(object sender, EventArgs e)
{
TextBox NumSerie = (TextBox) sender;
GridViewRow row = (GridViewRow) NumSerie.NamingContainer;
TextBox Symbole = (TextBox) row.FindControl("Symbole");
// ...
}
Note that i strongly advise against such helper classes in ASP.NET which hold and return database objects like your Sql.Instance.ObtenirConnexionSql(). It can be a source of nasty errors.

Related

Get textbox.text from nested gridview

I have a parent gridview with a child gridview
<!-- Parent -->
<asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="Grid"
DataKeyNames="SupplierReference" OnRowDataBound="gvParent_OnRowDataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<!-- Child -->
<asp:GridView ID="gvChild" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid"
ShowFooter = "true" OnRowDataBound="gvChild_OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText="Qty" ItemStyle-Width="100px">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("Qty")%>' />
</ItemTemplate>
</asp:TemplateField >
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelectQtys" runat="server"
CommandArgument = '<%# Eval("SupplierReference")%>' CommandName="SelectQtys"
OnClientClick = "return confirm('Add these materials to this task?')"
Text = "Add" OnClick="getQty" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am trying to have a textbox that the user can alter the value and when they click add I want to be able to pull that text into the C# code and work with it.
I cant get it into my C# code.
protected void getQty(object sender, EventArgs e)
{
//After clicking "add"....
//Do something here to get text from each TextBox1 in the Child gridview
}
Someone please help before I lose what little hair I have left...
protected void getQty(object sender, EventArgs e)
{
//After clicking "add"....
string s;
for(i=0; i < gvChild.Rows.Count; i++)
{
s = ((TextBox)gvChild.Rows[i].FindControl("TextBox1")).Text;
}
//Do what you want to with this string
}

Gridview on Content page RowCommand does not fire - ViewState?

The problem I'm having is the RowCommand of my GridView will not fire. I've read through millions of posts, and as a result I think I'm even more confused. So, if you can see what specifically it is I've done wrong here, please point it out.
I did ask a similar question a couple of weeks ago, but I was using a gridview nested in a datalist and using 'Include' Siblings of the EntityDataSource to display the Siblings, which are the many side of the relationship to Referral, it's fine for display, but figuring out Edit Update and Delete was nightmareish. So I've tied to simplify it, but am now stopped in my tracks because I'm losing controls somewhere in the postbacks.
I have a master page with a ContentPlaceholder:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.Master.cs" Inherits="HomelessStudent.Web.SiteMasterPage" ViewStateMode="Inherit" EnableViewState="True" %>
<asp:ContentPlaceHolder ID="ContentPlaceHolderAgent" runat="server">
</asp:ContentPlaceHolder>
On the Agent page-
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolderAgent" runat="server">
<asp:Panel ID="SiblingPanel" runat="server" ViewStateMode="Enabled" Visible="True">
<asp:GridView ID="SiblingGridView" runat="server" CssClass="grid"
AutoGenerateColumns="false"
DataKeyNames="Id"
ShowFooter="true"
OnDataBound="SiblingGridView_DataBound"
OnRowEditing="SiblingGridView_RowEditing"
OnRowUpdating="SiblingGridView_RowUpdating"
OnRowCommand="SiblingGridView_RowCommand"
OnRowDeleting="SiblingGridView_RowDeleting" ViewStateMode="Enabled" ClientIDMode="Static">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="SiblingName">
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("SiblingName") %>' ID="TextBox1"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("SiblingName") %>' ID="Label1"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="NewSiblingName" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="false">
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" ID="UpdateLinkButton" ></asp:LinkButton> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="False" ID="LinkButton2"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" ID="EditLinkButton" ClientIDMode="Static"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton runat="server" CommandName="AddNew" Text="Add" ID="AddNewLinkButton"></asp:LinkButton> </FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowHeader="True" HeaderText="Delete"></asp:CommandField>
</Columns>
</asp:GridView>
</asp:Panel>
Code behind (binding data here because show only those siblings that belong to a specific record, ID (Guid) for that record is in the queryString, maybe...
if (IsPostBack == false)
{
if (Request.QueryString["id"] == null)
{
if (Session["studentid"] == null)
{
Response.Redirect("StudentPage.aspx");
}
else
{
referral = GetMostRecentReferral((String)Session["studentid"]);
PopulateUI(referral);
}
}
else
{
referral = GetThisReferral(Request.QueryString["id"]);
PopulateUI(referral);
}
}
Then, in PopulateUI(referral)
some stuff...
FillSiblingGrid();
String studentId = ((referral.StudentID).ToString()).Trim();
getSelectedStudentDeatails(studentId);
Session["referralid"] = (Guid)referral.Id;
And fill siblings grid-
private void FillSiblingGrid()
{
if (referral != null)
{
List<Sibling> siblings = new List<Sibling>();
using (HomelessStudentDataEntities db = new HomelessStudentDataEntities())
{
siblings = (from s in db.Siblings
where s.ReferralID == referral.Id
select s).ToList();
}
if (siblings.Count > 0)
{
SiblingGridView.DataSource = siblings;
SiblingGridView.DataBind();
}
else
{
int TotalColumns = SiblingGridView.Rows[0].Cells.Count;
SiblingGridView.Rows[0].Cells.Clear();
SiblingGridView.Rows[0].Cells.Add(new TableCell());
SiblingGridView.Rows[0].Cells[0].ColumnSpan = TotalColumns;
SiblingGridView.Rows[0].Cells[0].Text = "No siblings found";
}
}
}
I faced the similar problem. Enabling the grid view state resolved the problem

GridViewRow not returning proper cells

So I have this problem with one of my pages, which basically lists out a bunch of comments for a specified student. The comments are supposed to be editable, but I'm having a problem with getting the contents of a row (so I can display the comment content in a TextBox and allow for edits).
The issue is that whenever I access the GridViewRow from the GridView like such:
this.CommentList.Rows[e.NewEditIndex]
It is returning a collection of cells, but whenever I try access the a cell like so: row.Cells[0].Text (where row is the selected GridViewRow object) it doesn't return any values.
Here is my .aspx code:
<asp:GridView ID="CommentList" runat="server" AutoGenerateColumns="False" CellPadding="5"
ShowHeader="false" Width="100%" DataKeyNames="CommentId" OnRowDeleting="CommentList_RowDeleting"
OnRowCancelingEdit="CommentList_RowCancelingEdit" OnRowEditing="CommentList_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<b>Author:</b>
<%# ((Comment)Container.DataItem).Author.Name %>
<br />
<b>Date:</b>
<%# ((Comment)Container.DataItem).Created %>
<hr style="border-top: solid 1px black" />
<div style="text-align: center;">
<asp:Panel ID="OptionsPanel" runat="server">
<asp:LinkButton ID="DeleteLinkButton" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this comment?');">Delete</asp:LinkButton>
|
<asp:LinkButton ID="EditLinkButton" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</asp:Panel>
<asp:Panel ID="EditOptionsPanel" runat="server" Visible="false">
<asp:LinkButton ID="CancelEditLinkButton" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</asp:Panel>
</div>
</ItemTemplate>
<ItemStyle CssClass="topLeftJustify" Width="200px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Panel ID="ViewCommentPanel" runat="server">
<%# ((Comment)Container.DataItem).Content%>
</asp:Panel>
<asp:Panel ID="EditCommentPanel" runat="server" Visible="false">
<asp:TextBox ID="Comment" runat="server" CssClass="textEntry" TextMode="MultiLine"
Width="100%" Height="100px"></asp:TextBox>
</asp:Panel>
</ItemTemplate>
<ItemStyle CssClass="topLeftJustify" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my .aspx.cs code (that relates to the code above):
protected void CommentList_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
GridViewRow row = this.CommentList.Rows[e.NewEditIndex];
((Panel)row.FindControl("OptionsPanel")).Visible = false;
((Panel)row.FindControl("EditOptionsPanel")).Visible = true;
((Panel)row.FindControl("ViewCommentPanel")).Visible = false;
((Panel)row.FindControl("EditCommentPanel")).Visible = true;
// problem is with this line. it doesn't show the contents of the "comment"
((TextBox)row.FindControl("Comment")).Text = row.Cells[0].Text;
}
catch (Exception ex)
{
this.Messages.ChangeMessage(ex.Message, MessageType.Error);
}
}
When you use a TemplateField you cannot use e.Row.Cells[index].Text to access a control text of the cell. I would simply add a Label to the panel.
But you can also try it this way:
Panel ViewCommentPanel = (Panel) e.Row.FindControl("ViewCommentPanel");
LiteralControl objPanelText = ViewCommentPanel.Controls[0] as LiteralControl;
TextBox Comment = (TextBox) row.FindControl("Comment");
Comment.Text = objPanelText.Text;

jquery datepicker does not set date in ASP.net gridview EditItemTemplate and FooterTemplate's textBox

I am trying to implement a VERY simple ASP.net page: A GridView that allows user to edit old entry or insert a new entry. One of the columns in the GridView is holiday, so I use Jquery's datepicker to allow user to select a date.
Here is the ASP.net code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView ID="GridView1" runat="server" Height="300px"
ShowFooter="True"
AutoGenerateColumns="false"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="txtEditDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>' OnLoad="DisplayDatePicker1" ReadOnly="true"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewDate" runat="server" OnLoad="DisplayDatePicker2" ReadOnly="true"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my DisplayDatePicker1 method, DisplayDatePicker2 would be very similar.
protected void DisplayDatePicker1(object sender, EventArgs e)
{
StringBuilder scriptText = new StringBuilder();
string clientID = (sender as TextBox).ClientID;
scriptText.Append("$(function() {");
scriptText.Append("var DateSelector1 = $('#" + clientID + "'); ");
scriptText.Append("DateSelector1.datepicker();");
scriptText.Append(" });");
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"DateScript1", scriptText.ToString(), true);
}
So far so good. User can see the popup Datepicker and pick a date when he/she clicks Edit in the GridView row. Howerver, The following is the problem
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtEditHoliday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditHoliday");
TextBox txtEditDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditDate");
DropDownList dpdCountry = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("dpdCountry");
//txtEditDate.Text is not set,
}
txtEditDate.Text still contains the old date. The value selected by user via JQuery datepicker is not being passed to the txtEditDate.Text Please help! I spent many hours to search the internet but have not found any solutions.
To get the new, revised values - use :
e.NewValues
(from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewupdateeventargs.aspx)

How to carry out edit mode to update datas in Datalist control?

i have a datalist control
<ItemTemplate>
<asp:Label ID="lblAddressID" runat="server" Text='<%# Bind("StudentName") %>'/>
<asp:Label ID="lbl" runat="server" />
<asp:Button runat="Server" ID="cmdEdit" CommandName="Edit" Text="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAddressID" runat="server" Text='<%# Bind("StudentName") %>' BackColor="#FFFF66" />
<%-- <asp:Label ID="lbl" runat="server"/>
<asp:Button runat="Server" ID="cmdUpdate" CommandName="Update" Text="Update" />
<asp:Button runat="Server" ID="cmdCancel" CommandName="Cancel" Text="Cancel"/>--%>
</EditItemTemplate>
</asp:DataList>
and during page load im binding the datas:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt = obj.GetDatas();
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
now i received the datas binded to the control. i need to update my datas in edit mode.
How to carry out edit mode to update datas in Datalist control ??
any help...
have look at this sample
EditItemTemplate and DataList
source code:
DataList3_cs.aspx

Categories

Resources