Conditional Image Template Column - c#

I am using Visual Studio 2015 and entity framework 6. I have a GridView and I want the status column on it to show four different types of images, depending on string in that field from the database. I want it to be done with a template.
Here is my GridView:
<asp:GridView ID="gvStatus" runat="server" Height="184px"
Width="1359px" AutoGenerateColumns="false" AllowSorting="true" >
<HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black"/>
<RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White"/>
<AlternatingRowStyle BackColor="#afadad" ForeColor="White" />
<Columns>
<asp:CommandField HeaderText="" SelectText="Delete" ShowSelectButton="true" ControlStyle-ForeColor="White" />
<asp:BoundField HeaderText="Status" DataField="Status" />
</Columns>
</asp:GridView>
How do I get the status column to show up with four different images, dependent on what string is there?

You could do it like this:
<Columns>
<asp:TemplateField >
<HeaderStyle Width="10%" />
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#GetImagePath(Eval("img").ToString())%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
And in the code behind:
public string GetImagePath(object value)
{
if (string.IsNullOrEmpty(Convert.ToString(value))) return string.Empty;
var x = int.Parse(value.ToString());
return x > 0 ? "Your Image Path" : "Default Image Path";
//Here I show two different types of images depending on int value in that field from the database you can change it to four type with if-else and also depending on string value
}

Related

GridView - Set focus to specific cell

I've seen lots of posts out there for this question, however, they all suggest we use methods like: dgv.CurrentCell or dgv.Rows[row].Cells[cellno].Selected. Intellisense finds no such methods. I have a textbox in a gridview, where I use the OnTextChanged method. Then, in my C# code, I update this quantity, then the grid refreshes automatically, and goes back to the top row, even though we've scrolled down a couple of pages. I've also tried putting in the MaintainScrollPositionOnPostback="true" in the 'Page' section of my .aspx page and that didn't seem to do anything. We're on .Net Framework 4.0.
<asp:GridView ID="gvOrderDetails" runat="server" AlternatingRowStyle-BackColor="#FAFAFA" Width="940px" AutoGenerateColumns="False" AllowSorting="True" OnSorting="SortOrderDetails"
OnRowCommand="gvOrderDetails_RowCommand" EmptyDataText="No Data to Display"
DataKeyNames="STOREORDNUM" HeaderStyle-Height="22px"
onselectedindexchanged="gvOrderDetails_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" /><EditRowStyle BackColor="#2461BF"/>
<FooterStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" />
<HeaderStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" BorderWidth="1px" BorderColor="Gray"/><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" Height="22px"/>
<Columns>
<asp:BoundField DataField="ITMCD" HeaderText="Item Code" SortExpression="ItemCode" >
</asp:BoundField>
....
<asp:TemplateField HeaderText="Order Qty" SortExpression="OrderQty" >
<ItemTemplate>
<asp:TextBox ID="OrderQty" runat="server" Width="36" MaxLength="5" class="numberinput" AutoPostBack="true" OnTextChanged="buttonUpdateQty_Click" Text='<%# Bind("ORDERQTY") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind, I've tried these two things:
gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty").Focus();
gvOrderDetails.Rows[row.RowIndex].Cells[7].Controls[0].Focus();
You need to cast the required cotrol cell into Textbox control and then call the Focus() method on it.
Try This:
TextBox txtOrderQty = (TextBox) gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty");
txtOrderQty.Focus();
Add a handler to SelectedindexChange Event of your grid view
Gridview1.SelectedRow.Focus();

How to get value of TextBox in ASP.NET

I have entered a value in the textbox, however when I clicked the button to get the value at server side, it still retrieved the old value.
Here is my code:
aspx:
<asp:GridView ID="gvTicketSkus" runat="server" AutoGenerateColumns="false"
CssClass="innergv" HeaderStyle-CssClass="innergvHeader" GridLines="Horizontal"
Width="570px">
<Columns>
<asp:BoundField HeaderText="Sku" DataField="TicketItemCode" />
<asp:BoundField HeaderText="TICKET TYPE" DataField="TicketItemCodeDescription" />
<asp:BoundField HeaderText="Tickets#" DataField="NumberOfWristbandsPerTicket" Visible="false" />
<asp:BoundField HeaderText="PRICE" DataField="Price" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="QUANTITY">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" TextMode="SingleLine" MaxLength="4" Width="80px" CssClass="quantity" Text="0"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#:
foreach (GridViewRow gvr in gvTicketSkus.Rows)
{
sku = gvr.Cells[0].Text;
quantity = Convert.ToInt32(((TextBox)gvr.FindControl("txtQuantity")).Text);
if (quantity > 0)
{
pendingOrder.Add(sku, quantity);
}
}
As you see when I get the value of txtQuantity, it gave me the old value, instead of the one I type in.
I guess there is some issue in postback.
You can try using
Request.Form[((TextBox)gvr.FindControl("txtQuantity")).ClientID];
To get exactly what was posted to the server.
You may need to work on the syntax. I can't test it right now.

Difference between <Fields> and <Columns> in <asp:GridView>

Well it so happens that I am kind of a novice to asp.net and trying to create a Grid whose source is declared programmatically.
In the process, I came across 2 tags Fields and Columns. Can anyone please tell me how they are different?
EDIT: I went through some sample MSDN examples, and for all I can tell it seems to me they can be used interchangeably(though I have a feeling thats not true!).
Check this out:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="ObjectDataSource1">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title"
SortExpression="Title" />
<asp:BoundField DataField="HireDate" HeaderText="HireDate"
SortExpression="HireDate" />
</Columns>
</asp:GridView>
And then there is:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateRows="False" DataKeyNames="ProductID"
DataSourceID="ObjectDataSource1" EnableViewState="False">
<Fields>
<asp:BoundField DataField="ProductName" HeaderText="Product"
SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName"
HeaderText="Category"
ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="SupplierName"
HeaderText="Supplier"
ReadOnly="True" SortExpression="SupplierName" />
<asp:BoundField DataField="QuantityPerUnit"
HeaderText="Qty/Unit" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice"
DataFormatString="{0:c}"
HeaderText="Price"
HtmlEncode="False" SortExpression="UnitPrice" />
</Fields>
</asp:GridView>
Seem similar or is it just me??!
Thanks for helping.
Columns is just the surrounding tag for the fields which are
TemplateFields with any controls you want or
BoundFields which are created automatically
So Columns enclose the list of fields in the GridView.
<Columns>
<asp:Boundfield datafield="StudentID"
readonly="true"
headertext="Student ID"/>
<asp:TemplateField HeaderText="Student" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:label runat="server" Font-Bold="true" ID="LblStudent" Text='<%# Bind("Student") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inner Grid">
<ItemTemplate>
<asp:GridView ID="Grid2" AutoGenerateColumns="false" runat="server" GridLines="None" Width="300">
<RowStyle CssClass="GridViewRowStyle" />
<AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
<HeaderStyle CssClass="GridViewHeaderStyle" />
<SelectedRowStyle BackColor="Aqua" />
<Columns>
<asp:TemplateField HeaderText="Student" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:label runat="server" Font-Bold="true" ID="LblStudent" Text='<%# Bind("Student") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
As you can see, a TemplateField could also contain another nested GridView.
Am I blind or wat!
After I posted this question I went back to my drawingboard and as it turns out, there is no Fields tag in asp:GridView, right?!
Please do let me know if this is true people(and prove me silly!)
Putting aside this particular control for a moment, it might be helpful to look at this from a general computer science point of view.
In classic programming (ANY LANGUAGE), a FIELD would be the INTERSECTION of a row and a column -- a discrete piece of data. For example, if a table has 20 rows of data containing first and last names, if you went to the 19th row and looked in the "first name" column, you've got a FIELD. Perhaps it contains the discrete data "JOHN".
COLUMNS then would be collections of like data -- in this example, you have the two columns "first name" and "last name". Columns would have attributes such as a data type, maximum length, constraints (are nulls OK?, etc.) and so forth.
Some may quibble with my definitions and say that individual cells in a COLUMN would be called a FIELD. It's not uncommon to hear that. I would reply that for a table with a single column, it'd be especially true :-) But the takeaway point is this: COLUMNS are generally containers for smaller, more discrete items such as FIELDS. FIELDS typically refer to a single piece of data, such as you'd find at the intersection of a row and column in a database table.

How to limit textbox template field text length in gridview?

<asp:GridView ID="CommentGrid" GridLines="None" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="No." DataField="Num" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField HeaderText="Subject Name" DataField="SubjectName">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:TextBox ID="CommentBox" runat="server" TextMode="MultiLine" CssClass="commentTbx" MaxLength="2"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The above Maxlength="2" doesnt work!! I even tried other method like databound, and foreach loop to code it but it still fails.
User RegularExpressionValidator. The following accepts minimum characters 0 and maximum 2 characters.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="CommentBox" ErrorMessage="Out of Range Max 2 Chars"
ValidationExpression=".{0,2}"></asp:RegularExpressionValidator>
MaxLength does not work on MultiLine mode.
Yes, it is because of TextMode="MultiLine" . You need some javascript to check total chars and impose limit.
Have you tried <EditItemTeplate> instead of <ItemTemplate>?

How do I make the gridview headers to links?

I want the headers of my gridview to be hyperlinks, without the "SortExpression"...
I searched the net, but I've been not very succesful.
Anyone has the solution?
For example: when clicking on the header of a simple gridview, the site navigates to a webpage. Is it possible?
Thanks in advance!
Have you tried Gridview Header template like...
<asp:GridView runat="server" ID="grd">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:HyperLink runat="server" NavigateUrl="YourURL"> </asp:HyperLink>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I think a HeaderTemplate is needed here...
Ref.: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.headertemplate.aspx
HTH.
Now I got this gridview, And I need the headers to be clickable, whereafter an event starts (something like OnClickHeader="header_ClickEvent"?) Ofcourse there is a SortExpression element, which enables to sort the grid, but I want to be able to start any event, like when clicking a button.
I could not find any solution within the asp:BoundField nor asp:TemplateField...
I thought a hyperlink could solve the problem, but that was a bit premature.
The Gridview:
<asp:GridView CssClass="gridview" ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Student_key" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" PagerSettings-Visible="false" PageSize="14">
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle"/>
<AlternatingRowStyle CssClass="altrowstyle" />
<Columns>
<asp:BoundField DataField="Studentnumber" HeaderText="Studentnummer" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="Prefix" HeaderText="Voorletters" >
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="prename" HeaderText="Voornaam" SortExpression="Voornaam">
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="nickname" HeaderText="Roepnaam" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="insertion" HeaderText="Tussenvoegsel" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="surname" HeaderText="Achternaam">
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:CommandField SelectText="show results" ShowSelectButton="True" >
<HeaderStyle CssClass="header100" />
</asp:CommandField>
</Columns>
<EmptyDataTemplate >There are no results shown, please try again.</EmptyDataTemplate>
</asp:GridView>
I used a method that might be a little unconventional but it works. In my case I wanted to use the standard BoundField controls in my gridview as opposed to using a template field with both a HeaderTemplate and ItemTemplate. I used a simple gridview based on a SQL datasource that looks like this.
<asp:GridView
ID="gvTopXByContest"
runat="server"
AutoGenerateColumns="False"
DataSourceID="dsTopXByContest"
AllowSorting="true"
OnSorting="gvTopXByContest_OnSorting" >
<Columns>
<asp:BoundField DataField="txtOnlineUserName" HeaderText="Fan Name & Rank" SortExpression="txtOnlineUserName" ItemStyle-Width="155px"></asp:BoundField>
<asp:BoundField DataField="fltTotalPoints" HeaderText="Points" SortExpression="fltTotalPoints" ItemStyle-Width="40px"></asp:BoundField>
<asp:BoundField DataField="curWon" HeaderText="Won" SortExpression="curWon" ItemStyle-Width="40px"></asp:BoundField>
</Columns>
</asp:GridView>
I then used code that fires on the OnSorting event of the gridview to do my redirects
Protected Sub gvTopXByContest_OnSorting(sender As Object, e As GridViewSortEventArgs)
If e.SortExpression <> DirectCast(sender, GridView).SortExpression Then
If e.SortExpression = "txtOnlineUserName" Then
Response.Redirect(URL to redirect to goes here)
ElseIf e.SortExpression = "fltTotalPoints" Then
Response.Redirect(URL to redirect to goes here)
Else
'I could have used another ElseIf here but since there are only 3 columns Else works
Response.Redirect(URL to redirect to goes here)
End If
End Sub

Categories

Resources