Convert Gridview column from ID to String in ItemTemplate - c#

I currently have a Gridview that displays
TypeID , Name , Description.
I would like to display the actual type name instead of the TypeID in the gridview. I created this function that takes in the ID and returns the Name but I am having trouble using it. There are 15-20 different types so How do I convert the TypeID to a Type Name so that it is displayed when the Gridview is rendered.
protected string GetGenericTypeByID(int genericTypeID)
{
string genericTypeName;
GenericType.Generic_TypeDataTable genericTypeNameDS = new GenericType.Generic_TypeDataTable();
genericTypeNameDS = GenericBO.Get_GenericTypeByID(genericTypeID);
genericTypeName = genericTypeNameDS[0]["Generic_Type_Name"].ToString();
return genericTypeName;
}
I thought I would be able to use the function in the ItemTemplate but it seems to be harder that I thought
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("GetGenericTypeByID("Generic_Type_ID")")%>'></asp:Label>
</ItemTemplate>
Thanks to Everyone who helped me solve this problem.
I ended up using the method below and it works perfectly.
GetGenericTypeByID( Convert.ToInt32(Eval("Generic_Type_ID")))

You've got the 'bind/eval' and method call inside out.
See Using Method inside a DataGrid or GridView TemplateField
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<a href='<%# FormatUrl(Eval(”email1″).ToString())%>'><%# Eval(”fname”) %>, <%# Eval(”lname”) %></a>
</ItemTemplate>
With the 'FormatUrl' function being:
public string FormatUrl(string email)
{
return “mailto:” + email;
}

Are you limited to a label tag? If not, Expanding on David HAust's answer try the following:
<ItemTemplate>
<%#GetGenericTypeByID(Eval(Generic_Type_ID))%>
</ItemTemplate>

Create a read-only property on the row class that you're using to populate the grid, and get this property to return the results of your function.

Related

How to display a Navigation Property of a table inside a Data control like a FormView?

Ok I have a many to many relationship like this:
Walk = {WalkID, title, ...., (Navigation Properties) Features}
Feature = {FeatureID, featureName, description, (Navigation Properties) DogWalks}
I do of course have a junction table, but EF assumes this thus it is not shown in my edmx diagram:
WalkFeatures = {WalkID, FeatureID} //junction, both FK
So using LINQ with EF, I am now trying to grab the features for the Walk at WalkID=xx.
This is my formview:
<asp:FormView ID="FormView1" runat="server" ItemType="Walks.DAL.Walk" SelectMethod="FormView1_GetItem">
<ItemTemplate>
<h1><%# Item.Title %></h1>
...
</ItemTemplate>
</asp:FormView
<asp:Label ID="lbFeatures" runat="server" Text="Label"></asp:Label>
And selectMethod:
public Walks.DAL.Walk FormView1_GetItem([QueryString("WalkID")] int? WalkID)
{
using (WalkContext db = new WalkContext())
{
var walk = (from n in db.Walks.Include("Features")
where n.WalkID == WalkID
select n).SingleOrDefault();
foreach(var f in walk.Features){
lbFeatures.Text += f.FeatureName + "<br/>";
}
return walk;
}
}
The code runs fine, but is there a way that I can display the Walk.Features directly inside the <ItemTemplate> of the formview rather than using a label and a loop? Can the attribute be directly binded like the other properties in the .aspx page?
I have also used this new feature not that extensively but just gave it a try for this particular scenario and this is what I have:-
Simply return walk from FormView1_GetItem method and don't manipulate your label control there. Now, you can use a Repeater control to display the lbFeatures control (since it is going to repeat dynamically) like this:-
<ItemTemplate>
<h1><%# Item.Title %></h1>
<asp:Repeater ID="lbFeatures" runat="server" DataSource='<%# Item.Features%>'>
<ItemTemplate>
<asp:Label ID="lblTest" runat="server"
Text='<%# Eval("FeatureName") %>'></asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
As you can see I am able to assign the datasouce of repater control as Item.Features, then use the conventional approach to bind the label. This looks clean and simple :)

asp.net c# using if conditions with Bind

with asp.net c# I get the code of a country with bind :
<asp:Label runat="server" Text='<%# Bind("h_country") %>' ID="Label1"></asp:Label>
this return code of country like usa, tr, eg, il.
I need to put if conditions and I try to do it like this:
<asp:Label runat="server" Text='<%# if(Bind("h_country")=="usa") resonse.write("United States"); %>' ID="Label1"></asp:Label>
note: I'm using GridView and template.
I tried alo at code behind to get the value of country like this:
String s = Lable1.Text;
but also not workes!
how can I get it as a variable and use if condition ?
You need to use find control if thus label is within the gridview and then get the sting from label.
You probably want to handle this in the code behind
<asp:Label runat="server" Text='<%# GetCountry(Eval("h_country")) %>' ID="Label1"></asp:Label>
code behind
public string GetCountry(object country)
{
if (county.ToString() == "usa")
return "United States";
}
It would be better if you had a lookup so you don't have to have a lot of if statements
This is how you can do conditional checks in the markup while binding. Try something like below but I would not advise doing this kind of conditional checks and response.write at the template level but do it in code behind.
<asp:Label runat="server" Text='<%# Bind("h_country") == "usa" ? "United States" : (string)Bind("h_country") %>' ID="Label1"></asp:Label>
And this is how you can do it at code behind. Use the databound event to find the Label1 and set the appropriate text in there.
You need to define OnRowDataBound="gvTest_DataBound for the gridview in the markup
protected void gvTest_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblCountry = (Label)e.Row.FindControl("Label1");
if (lblCountry.text == "usa"){
// do something here
}
else {
// do something otherwise
}
}
}

string.replace databound column in Gridview

Im currently pulling a string comment from a DB into a gridview to display to the user. Throughout the string i have placed <br/>s where i want linebreaks, but am wondering how to replace the <br/>s with "Environment.Newline"s. the column is simply a boundfield.
<Columns>
<asp:BoundField HeaderText="Comment" DataField="UAComment" />
</Columns>
and im populating the table with an adapter and Fill():
adapter = new SqlDataAdapter(queryString, connection);
connection.Open();
adapter.SelectCommand = command;
recordsFound = adapter.Fill(table);
results.Text = recordsFound + " records matching query";
connection.Close();
Thanks for any info.
ps: also tried already building the string/submitting the string to the database with newlines but cant seem to get it to pull out of the db with the proper formatting.
public void Group(String message)
{
log.Append(": Group :");
log.AppendFormat(message);
log.Append("<br/>");
}
public String GetLog()
{
log.Replace("<br/>", Environment.NewLine);
return log.ToString();
}
also substituted "Environment.Newline" with #"\n", "\n", #"\r", "\r"
The easiest solution would be use a template field instead of bound field and add bind a literal in the template field with current column value. Using this it will render all the stuff in html format and the line breaks come autometically.
Example :
<asp:TemplateField>
<HeaderTemplate>
Comment
</HeaderTemplate>
<ItemTemplate>
<asp:Literal runat="server" ID="Literal1" Text='<%# Eval("UAComment") %>' />
</ItemTemplate>
</asp:TemplateField>
Hope this will fix you problem

Populate a table on an ASP.NET page

Simple question regarding table(single column in this case) population.
As much as it may seem like an easy question, I've never been involved in the front-end area, so here it goes.
The layout is 2 columns and 8 rows.
Something like.
Name A
LastName B
Age C
BirthDate D
...
Column 1 are stable, "titles" if you want, that won't change.
A,B,C,D are the result of querys to a database. So, options I can think of are:
Draw a 2Column - 8Row table and place TextBoxes in A,B,C,D... fields. So later on they can be populated with the results of the query (This option is not the most "beautiful" one since TextBoxes alter the design intented to be absorved by the whole page using .CSS files.
Set a datagrid. The problem here I think is that some of the A,B,C,D fields will have to be changed for later query-usage. And I'm not sure if Datagrids are ment for that.
Is there a "good-way" for me to solve this issue?
Thanks in advance.
EDIT.
A,B,C,D data is held in a DataSet.
To me, the way you're describing the data doesn't really lend itself too well for a DataGrid. This control works best for data that you plan to display in a standard tabular style, where the column names go across the top and then you display the row(s) of values underneath. It's also a little unclear to me if you are intending to bind one or many instances of your Object (which I will just call Person for now) to the UI.
Let's go ahead and define that object:
public class Person {
public String Name { get; set; }
public String LastName { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }
}
To bind a single instance of Person to your UI, a simple HTML table should work fine. I'm using TextBoxes to display the values here, but if you don't need to edit them then just use Labels instead.
<table>
<tr><td>Name:</td><td><asp:TextBox ID="txtName" runat="server" /></td></tr>
<tr><td>Last Name:</td><td><asp:TextBox ID="txtLastName" runat="server" /></td></tr>
<tr><td>Age:</td><td><asp:TextBox ID="txtAge" runat="server" /></td></tr>
<tr><td>Birthdate:</td><td><asp:TextBox ID="txtBirthDate" runat="server" /></td></tr>
</table>
It's pretty trivial at this point to bind the properties from Person to their respective controls on the page using the code-behind.
If you wanted to use this same layout to display multiple instances of Person on a page, go with the ASP.net Repeater. The markup for this would look more like:
<asp:Repeater ID="repPeople" runat="server">
<ItemTemplate>
<table>
<tr><td>Name:</td><td><asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>' /></td></tr>
<tr><td>Last Name:</td><td><asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' /></td></tr>
<tr><td>Age:</td><td><asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' /></td></tr>
<tr><td>Birthdate:</td><td><asp:TextBox ID="txtBirthDate" runat="server" Text='<%# String.Format("{0:d}", Eval("BirthDate")) %>' /></td></tr>
</table>
</ItemTemplate>
</asp:Repeater>
In the code-behind, you just bind a collection of Person to the DataSource property on the Repeater:
protected void Page_Load(object sender, EventArgs e) {
// A simple example using Page_Load
List<Person> people = new List<Person>();
for (int i = 0; i < 10; i++) {
people.Add(new Person() {Name = "Test", Age = 10, BirthDate=DateTime.Now, LastName = "Test"});
}
if (!IsPostBack) {
repPeople.DataSource = people;
repPeople.DataBind();
}
}
Note: You could accomplish a similar layout using CSS instead of tables, however the same principles apply between binding a single vs multiple objects. Just replace the table layout in this example with whatever markup you ultimately define.
There's a table control in WebForms that you should be able to populate from a DataSet see the MSDN docs: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.table.aspx

Display image based on a value in asp GridView column

I have a gridview and one of the template fields is an asp image server tag. I want to display an image in this gridview but based on the value that I obtain on databind.
So, every row can have a different values and based on these values I need to display different images. I tried to call a javascript function GetImage() and pass the value that I obtain on databind to this function. But, I cannot get this to work.
<Columns>
<asp:TemplateField HeaderText="<%$Resources:LocalizedText,LabelStatus%>">
<ItemTemplate>
<asp:Image ID="imgStatus" runat="server" CssClass="label" src="GetImage(<%#Eval(<%# Bind("Status_value") %>) %>)"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Javascript function -
function GetImage(value)
{
if (value == 1)
{
return "../Images/act_green.gif";
}
else
{
return "../Images/act_red.gif";
}
}
What am I doing wrong here? And, how can I fix it? Thanks
Unless you have more needs that you haven't mentioned, there is no need to use Javascript and you might as well do everything on the server.
Change your asp:image tag to the following:
<asp:Image ID="imgStatus" runat="server" CssClass="label" ImageURL='<%# GetImage((int)Eval("Status_Value")) %>' />
In your code-behind, place the following:
public static string GetImage(int value)
{
if (value == 1)
{
return "../Images/act_green.gif";
}
else
{
return "../Images/act_red.jpg";
}
}
And you're done.
Your GetImage function is not executed.
See:
IMG SRC tags and JavaScript
Server side code can return the path to the image without using JS.

Categories