Render the content of a TemplateField dynamically - asp.net

I want to know if there is a way of dynamically render the content of a template field from a GridView.
This is how the grid looks and what I want, is to somehow get the rendered string of the label in the code behind.
<asp:GridView runat="server" ID="simpleGrid" AutoGenerateColumns="false" Visible="false">
<Columns>
<asp:TemplateField HeaderText="Templated Date">
<ItemTemplate>
<asp:Label ID="firstLabel" Text='<%# Eval("Date") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Thanks in advance,
Kali.

Well, the only way to get the content of a control is to use the RenderControl method, via something like:
StringWriter strings = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(strings);
Label label = //find the reference to the label
label.RenderControl(html);
This should push the control's markup into the html writer and easily extracted through the string writer. That's one way. Otherwise, no direct way to access its HTML except in client-side javascript.
HTH.

Related

How to get Text box value from Grid view header template?

I want grid view header template textbox value. I write code for getting value but it return null.
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" ></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And On the code behind.cs i write that code but it returns null
protected void getTextBoxValue(object sender, EventArgs e)
{
//TableCell cell1 = TrackerGrid.HeaderRow.Cells[0];
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox) ;
string mobile = mobilenumber.Text;
How can I resolve this ? please help me!
I've just had a similar problem by trying to get textbox text from the footer row. I'm not sure if this is the best way to get around this problem but this should work if FindControl() successfully assigns the textbox.
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = Request.Form[mobilenumber.UniqueID];
EDIT: As VDWWD commented, Request.Form is a bad practice. But for my particular usage I couldn't find any other way to get the data from a textbox on button click due to my unorganized postbacks.

Asp.net gridview edit without editbutton

I have regular asp.net gridview,and i want to enable editmode in each row,and also without editbutton (like excel grid).
Edited data i want to save to my database by clicking "Post" button outside the grid(one button for whole grid).
How can i reach it?
To achieve this, you are going to have to use ItemTemplates for each column with textboxes in them as the control..
ASP
<asp:TemplateField HeaderText="Heading Title" SortExpression="Heading Title">
<ItemTemplate>
<asp:TextBox ID="tbTextbox" runat="server" Width="65px" Text='<%# Bind("ColumnNameYouWantToView") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
After this is set up properly, you will want the post button. You can either put it in the grid or outside the grid. I use both, but here is the one inside the grid as a footer.
ASP
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" Width="40px" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ValidationGroup="UPDATE" ID="btnUpdate" OnClick="btnUpdate_Click" runat="server" Text="Update" Width="50px"></asp:Button>
</FooterTemplate>
<FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
So far, what I have found that works best is using a foreach statement in your button click. The biggest flaw with this idea is that it will update every single row. It works, but if you only change a single row at a time, it will update all of them. I have my pager set to 10, so 10 rows are always updated (unless you are just searching for a single record and update it, the only that single record is updated).
Code Behind C#
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString);
conn.Open();
//finds the controls within the gridview and updates them
foreach (GridViewRow gvr in gvGridViewName.Rows)
{
string ID = (gvr.FindControl("lblId") as Label).Text.Trim();//finds the control in the gridview
string anotherControl = ((TextBox)gvr.FindControl("tbTextBox")).Text.Trim();//finds the textbox in the gridview
//Your update or insert statements
}
This is how I do it. You can also look into Real World Grids but I haven't had much luck with this as I would always get an error if a textbox was empty. This however, is suppose to be "smart" enough to just update the rows that have been changed, but again, I didn't have much luck of doing it this way. Hope this helps!

Is it possible to set up declarative control binding in the codebehind?

In ASP.NET WebForms, you can be all like:
<ItemTemplate>
<asp:Label ID="mylabel" Text='<%#Eval("myvalue") %>' runat="server"></asp:Label>
</ItemTemplate>
This declarative binding gets the value from the proper column/member in the datasource. Is it possible to do this in the codebehind:
mylabel.Text = String.Format("<%# Eval(""{0}"") %>", ControlName)
Edit: inb4 have you tried it? Yes. I will add that there's some parsing somewhere that actually prevents that string from showing when my grid binds, so I know I am touching onto something here.

Using hyperlink with querystring for gridview row

Is there someway to turn the row of a gridview into a hyperlink so that when a user opens it in a new tab for example, it goes to that link? Right now I am using a LinkButton and when the user opens it in a new tab, it doesn't know where to go.
I figured the .aspx code would look something like:
<asp:TemplateField>
<ItemTemplate>
<Hyperlink ID="hyperlink" runat="server" ForeColor="red" HtmlEncode="false" navigationURL="testUrl.aspx"
</ItemTemplate>
</asp:TemplateField>
The only thing is, our URLs are set up in the C# code behind as a query string, so I'm not sure how to pass that into the navigationURL section.
I'm guessing there's something I can do on the page_load with the query string to redirect to the page I need, but this is my first time working with query strings so I'm a little confused.
Thanks!
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/controller.aspx?routeID1={0}&routeID2={1}", Eval("routeid1"), Eval("routeid2"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
routeid1 and routeid2 are passed as query strings to the controller of that page.
What I did recently is modified my class to have a readonly property that constructs the A tag for me. This way I have control over what gets displayed; just text or a link.
<ItemTemplate>
<asp:Label ID="ColumnItem_Title" runat="server" Text='<%# Bind("DownloadATag") %>'> </asp:Label>
</ItemTemplate>
The code behind just binds an instance of the class to the gridview. You can bind the gridview whenever, on load on postback event, etc.
Dim docs As DocViewList = GetViewList()
GridViewDocuments.DataSource = docs
GridViewDocuments.DataBind()
In the above code, the DocViewList, instantiated as docs, is a list of a class that has all the properties that are needed to fill my GridView, which is named GridViewDocuments here. Once you set the DataSource of your GridView, you can bind any of the source's properties to an item.
Something like:
<asp:LinkButton ID="LinkButton_Title" runat="server" target="_blank"
PostBackUrl='<%# Eval(Request.QueryString["title"]) %>'
or binding them from the RowCreated event:
protected void GridView_OnRowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.FindControl("LinkButton_Title") as LinkButton).PostBackUrl = Request.QueryString["title"]))
}
}

asp.net HyperLinkField Has no ToolTip property (Alt text)

I wish there was a ToolTip field in HyperLinkField as there is one in HyperLink.
I'm creating a HyperLinkField by code before binding to my data source:
HyperLinkField hl = new HyperLinkField();
hl.DataNavigateUrlFields = new string[] { "col" };
hl.DataNavigateUrlFormatString = "{0}";
hl.DataTextField = "Foo";
Is there any way to also set a value to something which will render as a tooltip (or alt text)?
Any help will be appreciated.
That's correct, there's no tooltip/alt text property in a HyperlinkField. To get around this shortcoming, you need to use a template field and add a regular Hyperlink control.
<asp:TemplateField HeaderText="Href">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#
Eval("Href") %>' Text='<%# Eval("Href") %>' ToolTip='<%# Eval("Text") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
However, doing this in a programmatic requires a lot of work. You need to create your own class that implements the ITemplate interface. Here's a tutorial on that.
Your requirement can be accompished in <asp:HyperlinkField> itself by adding tooltip for that specific cell in RowDataBound event of a GridView. After binding the GridView to your DataSource you can do this in a RowDataBound event as follows:
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].ToolTip = "Your tooltip text";
}
Though you have accepted another answer, my answer may be helpful for some other users!

Resources