I am using a gridview to display information on a page. The condition is that when I get Y from database result I need to bind /images/goldx.png Else /images/check.gif how can I do that I am using asp.net with vb.net as backend
<asp:GridView ID="grdLocation" runat="server" Width="100%" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Monthly" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblLotName" runat="server" Text='<%#Eval("is_monthly") %>'></asp:Label>
<asp:Image ID="resultImage" runat="server" ImageUrl='<%# Eval("is_monthly") == 'Y' ? "~/Images/check.gif" : "~/Images/goldx.png" %>' />
</ItemTemplate>
</asp:TemplateField>
<Columns>
</asp:GridView>
My code for binding the Gridview :
Protected Function bindLocations()
Try
Dim _ds As DataSet
If _locComp Is Nothing Then
_locComp = New LocationComponent()
End If
_ds = _locComp.GetAllLots()
If _ds.Tables(0).Rows.Count > 0 Then
grdLocation.DataSource = _ds
grdLocation.DataBind()
End If
Catch ex As Exception
End Try
End Function
Thanks for your comment and answers .
You can do this check OnRowDataBound event of GridView. Like
Private Sub grdLocation_OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles grdLocation.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblLotNametxt as String = CType(e.Row.FindControl("lblLotName"),Label).Text
If lblLotNametxt = "Y" Then
CType(e.Row.FindControl("resultImage"),Image).ImageUrl = "~/Images/check.gif"
Else
CType(e.Row.FindControl("resultImage"),Image).ImageUrl = "~/Images/goldx.png"
End If
End If
End Sub
Hope this helps you.
Related
I have a drop down list 'Country', 'city' text box and an 'Add' button. The country drop down is NOT mandatory so I can just add a city without a country, adding an empty 'country' to the gridview works OK. the problem when I click on 'Edit' in the gridview it binds it to the first country in the list it does not just show a blank:
<asp:DropDownList ID="DDLCountry" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DDLCountry_SelectedIndexChanged" InitialValue="">
<asp:ListItem Text="------------------------ Select ------------------------" Value="" />
</asp:DropDownList>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:Button ID="btnNewLList" runat="server" OnClick="btnNewLList_Click" Text="Add new Country"/>
<asp:GridView ID="gvAddNewCountry" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowCommand="gvAddNewCountry_RowCommand" OnRowDeleting="gvAddNewCountry_RowDeleting" OnRowDataBound="gvAddNewCountry_RowDataBound" OnRowUpdating="gvAddNewCountry_RowUpdating" OnRowEditing="gvAddNewCountry_RowEditing" OnRowCancelingEdit="gvAddNewCountry_RowCancelingEdit" ShowHeaderWhenEmpty="True">
<EmptyDataTemplate>
No Data
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true">
</asp:CommandField>
<asp:TemplateField HeaderText="Country>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<% #Eval("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDCountry" runat="server" AppendDataBoundItems="True" AutoPostBack="false"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
Code behind:
Protected Sub gvAddNewCountry_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Edit" Then
Dim rowCountryToEdit As Integer = e.CommandArgument
Dim ddListCountry As DropDownList = (CType(gvAddNewCountry.Rows(CInt(e.CommandArgument)).FindControl("DDCountry"), DropDownList))
ddListCountry.DataSource = (From x In Country Where x.Domain = "lCountry" Order By x.Description Select x).ToList()
ddListCountry.DataTextField = "Description"
ddListCountry.DataValueField = "ID"
ddListCountry.DataBind()
End If
End Sub
Thanks for your help X
Ok, so when you have/want a ddl in a gv row?
We require TWO steps.
First step: Load up the list of choices for the dll
2nd step: set the ddl to the current row value, or blank (no choice) if null no value exists yet for the current row. This ALSO means we have to get/grab the current row value for the dll, and set the ddl to reflect this existing choice.
So, this is a two step process.
And the "event" we typical use for this is the row bind event. (all such controls from listview, gridview and more have this event).
Also, a VERY nice helper tip? During (but ONLY during) the data bind event, you have FULL USE of ALL columns from the data source - EVEN COLUMNS NOT in the gv!!!
I don't have a entity database first setup that you have, but lets load up a gv with a combo box:
So, our gv:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover" Width="50%"
DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="First Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Descripiton" />
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:DropDownList ID="cboRating" runat="server"
DataTextField="Rating"
DataValueField="ID">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And our code to fill is this:
Dim rstRating As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
' get data for rating combo
rstRating = MyRst("SELECT ID, Rating FROM tblRating ORDER BY ID")
' get data for grid
GridView1.DataSource = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
GridView1.DataBind()
End Sub
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Note VERY carefull in above, I created a page wide (class wide) data table called rstRating. This will go out of scope after the data bind, but we ONLY need it to persit DURING the gv data bind operating (since for each row of the gv, we don't want to run that query over and over - we need this same pick list for the dll).
Ok, so now we see/get this:
The only part we need is to load up the dll, and set it for each row. We use the RowDataBound event.
So, code for that was this:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
' bind drop down for each row
If e.Row.RowType = DataControlRowType.DataRow Then
' get combo
Dim rDrop As DropDownList = e.Row.FindControl("cboRating")
rDrop.DataSource = rstRating
rDrop.DataBind()
rDrop.Items.Insert(0, New ListItem("Please Select", "0"))
' now get current row value for rating.
Dim gData As DataRowView = e.Row.DataItem
If IsDBNull(gData("Rating")) = False Then
rDrop.Text = gData("Rating")
End If
End If
End Sub
So, for each row, get the dll.
For for that row, load up with choices
And THEN for that row, set the ddl to the current row value (but check for null, and don't set - it will then show our "select" choice value.
Hi I am using following code to display a grid on aspx
<asp:GridView Caption="Search Results" ID="PhysicianGrid"
runat="server" EnableSortingAndPagingCallbacks="false" PageSize="5" Style="width: 100%"
PagerSettings-Visible="false" AutoGenerateColumns="false" CssClass="grid" RowStyle-CssClass="gridDataRow"
HeaderStyle-CssClass="headerRow" EnableViewState ="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<HeaderStyle Width="70px" HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:LinkButton ID="SelectedPhysician" runat="server" Text="Select" CommandName="SelectAffiliation" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Physician ID" DataField="AMDM_Phys_ID" HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" HeaderStyle-Width="70px" ItemStyle-Width="70px" />
</Columns>
</asp:GridView>
and following is the row bound function for the above grid
Private Sub PhysicianGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles PhysicianGrid.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim selectLink As LinkButton = DirectCast(e.Row.FindControl("SelectedPhysician"), LinkButton)
Dim physId As String = e.Row.Cells(1).Text
If OperationType.Value.Equals("ADD ALLOCATION") Then
selectLink.OnClientClick() = String.Format("DisplayUpdateAllocationDivFromSearch('{0}');", physId)
Else
'selectLink.OnClientClick() = String.Format("DisplayUpdateAllocationDivFromSearchNewPhy('{0}');", physId)
selectLink.CommandArgument = physId
End If
selectLink.CommandArgument = physId
End If
End Sub
when I am clicking on the select link the application gets postback and hitting the page_load function but on the click event handler
Private Sub PhysicianGrid_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles PhysicianGrid.RowCommand
If _requestView.CRTypeId = Resources.PageResources.CRTYPEAddNewPhysician AndAlso Request.Form("__EVENTTARGET").Contains("SelectedPhysician") AndAlso OperationType.Value.Equals("ADD NEW PHY") Then
Dim selectedPhys As Integer = CInt(e.CommandArgument)
Dim tempPhys As PhysicianView = New PhysicianView
tempPhys.LoadSearchPhysician(Master.Environment, selectedPhys, True)
Dim dt As ShipToDetailsDataSet.AMU_SHIPTO_ALLOCATION_VDataTable = New ShipToDetailsDataSet.AMU_SHIPTO_ALLOCATION_VDataTable
If allocationOperation.Value.Equals("UPDATE") Then
If GridSelectedShipToAllocations.Rows.Count > 0 Then
For Each row As GridViewRow In GridSelectedShipToAllocations.Rows
Dim allocationString As String = DirectCast(row.FindControl("TextBoxNewAllocation"), TextBox).Text
SaveGridAllocationChangeForPostback(allocationString)
dt.AddAMU_SHIPTO_ALLOCATION_VRow(CInt(_shipToID), CInt(row.Cells(GridSelectedShipToAllocations_columns.colAMDM_PHYS_ID).Text), row.Cells(GridSelectedShipToAllocations_columns.colPhysician_Name).Text, Nothing, CDec(row.Cells(GridSelectedShipToAllocations_columns.colAllocation).Text.Substring(0, row.Cells(GridSelectedShipToAllocations_columns.colAllocation).Text.Length - 1)), CDate("01/01/2007"), Nothing, "", "", "", row.Cells(GridSelectedShipToAllocations_columns.colMajorSpec).Text.Replace(" ", ""), row.Cells(GridSelectedShipToAllocations_columns.colSecondarySpecialty).Text.Replace(" ", ""), row.Cells(GridSelectedShipToAllocations_columns.colTertiarySpecialty).Text.Replace(" ", ""), "", "", "", "")
Next
End If
dt.AddAMU_SHIPTO_ALLOCATION_VRow(CInt(_shipToID), tempPhys.PhysicianID, String.Format("{0}, {1} {2}", tempPhys.LastName, tempPhys.FirstName, tempPhys.MiddleName), Nothing, 0, CDate("01/01/2007"), Nothing, tempPhys.StatusId, tempPhys.FirstName, tempPhys.LastName, tempPhys.MajorSpec, tempPhys.SECONDARY_SPECIALTY_LD, tempPhys.TERTIARY_SPECIALTY_LD, "", "", "", "")
GridSelectedShipToAllocations.DataSource = dt
GridSelectedShipToAllocations.DataBind()
GridSelectedShipToAllocations.Style("display") = "block"
'DivAddAllocationChange.Style("display") = "none"
LabelTotal.Style("display") = "block"
ScriptManager.RegisterStartupScript(Me.PhysicianGrid, GetType(Page), "hideSearchPhysDiv", "DisplayUpdateAllocationDivFromSearchNewPhy('" + selectedPhys.ToString + "');", True)
End If
End If
End Sub
how can I get it to hit the row command function
P.S. I need to use the EnableViewState ="False" attribute in the grid I cant remove this attribute. Is there any workaround to this issue?
This is how I achieved it in a recent project, may be it could help you find the problem. The command argument has been specified in the ASPX instead of RowDataBound event.
As a work around you may just comment out the code in your RowDataBound event and set CommandArgument in ASPX and check what happens.
Also I think instead of Request.Form("__EVENTTARGET").Contains("SelectedPhysician") you may try e.CommandName.Equals("SelectedPhysician")
ASPX:
<asp:GridView ID="gvStudents" runat="server" AutoGenerateColumns="false">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="BtnUnlock" runat="server" Text="Unlock" CausesValidation="True" CommandName="UnlockProfile" CommandArgument='<%# Eval("User_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
CodeBehind:
Private Sub gvStudents_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvStudents.RowCommand
If e.CommandName.Equals("UnlockProfile") Then
Dim lnUser_ID As Integer = Convert.ToInt32(e.CommandArgument)
...
ElseIf e.CommandName.Equals("LockProfile") Then
...
End If
End Sub
I am having a lot of trouble getting a dropdown to bind with data from my database with the appropriate departments.
This is what I have so far:
HTML:
<asp:GridView ID="gridDepartmentHistory" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Visible="true" Text='<%# Eval("Department")%>'></asp:Label>
<asp:DropDownList ID="ddlDepartment" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Start Date" HeaderText="Start Date" />
<asp:BoundField DataField="End Date" HeaderText="End Date" />
</Columns>
</asp:GridView>
Code behind:
Protected Sub gridDepartmentHistory_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gridDepartmentHistory.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ddlDepartment As DropDownList = CType(e.Row.FindControl("ddlDepartment"), DropDownList)
Dim list As ICollection(Of Department) = Department.hrGetDepartmentList() 'Class method to fill a collection of items with the Department's Name and ID
ddlDepartment.DataSource = list
ddlDepartment.DataTextField = "Name"
ddlDepartment.DataValueField = "ID"
ddlDepartment.DataBind()
Dim dept As String = CType(e.Row.FindControl("lblDepartment"), Label).Text
ddlDepartment.Items.FindByText(dept).Selected = True
End If
End Sub
When I run this it throws an exception saying:
Object reference not set to an instance of an object.
BTW: I am using this tutorial to help me through: http://www.aspsnippets.com/Articles/How-to-populate-DropDownList-in-GridView-in-ASPNet.aspx
Any help would be greatly appreciated! Thank you!
You simply need to retrieve dept id and store it in gridview as hidden (if you don't want to display it).
Dim dept As String = CType(e.Row.FindControl("lblDepartmentId"), Label).Text
ddlDepartment.SelectedValue = dept;
Hope it helps.
Your problem is that you ara trying to find the contorl in the row but is inside a table cell.
Try this.
Dim cbo As DropDownList = CType(YourDGV.Rows(x).Cells(0).FindControl("ddlDepartment"), DropDownList)
i have this code:
Dim txt = CType(GridView1.FindControl("cnt_content"), TextBox)
txt.Attributes.Add("style", "word-wrap:break-word;")
i'm always getting that txt is an object not set to an instance of an object
that's my asp code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="cnt_id">
<Columns>
<asp:TemplateField HeaderText="Content">
<EditItemTemplate>
<asp:TextBox ID="cnt_content" runat="server" Text='<%# Bind("cnt_content") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcnt_content" runat="server" Text='<%# Bind("cnt_content") %>'></asp:Label>
</ItemTemplate>
<ItemStyle wrap="true" Width="400px" />
</asp:TemplateField>
any help?
My guess is that you are trying to find this control in the RowDataBound event, like this:
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
End Sub
You need to only check for this control on data rows, not header or footer rows, as the control will not exist in those other types of rows, try this:
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
' Only check in data rows, ignore header and footer rows
If e.Row.RowType = DataControlRowType.DataRow Then
' Determine if you are in edit mode or not
If GridView1.EditIndex = -1 Then
' Not in edit mode so look for label control defined in ItemTemplate of grid view
' Put logic here for label control
Else
' In edit mode so look for textbox control defined in EditItemTemplate of grid view
Dim txt = CType(GridView1.FindControl("cnt_content"), TextBox)
txt.Attributes.Add("style", "word-wrap:break-word;")
End If
End If
End Sub
It means that GridView1.FindControl("cnt_content") is returning null, which likely means that GridView does not directly contain a control called "cnt_content".
I am creating a WEB report in Visual Studio 2010 in VB.net. The report needs to display a table (please see the attached image). I am thinking to use the GridView component which i think it's the most appropriate one to choose. In the database there are students' data and marks. I can't alter the database in any way and i have to use Visual Studio 2010 with VB.
What i need to do is to show 3 different pictures(for example) depend on the student's marks. I got the pictures file in PNGs but this can be flexible.For example, over 70 will be a Smile picture. over 60 will be the Normal face. and over 40 will be the picture with no smile. I bit difficult for me to explain but i hope u get my point.
So pls advice me how can i achieve this. I am quite a newbie to this pls put as detail as you can. if there is a choice between client and server side script, i prefer server side script. Data source can be flexible (sql, or linq or anything).
You should use RowDataBound to bind data to controls in your GridView.
Following is a complete sample with aspx and codebehind(says more than thousand words):
<style type="text/css">
.GridViewRowStyle
{
background-color: #A0CFEC;
color:Blue;
}
.GridViewAlternatingRowStyle
{
background-color:White;
color:#15317E;
}
.GridViewHeaderStyle
{
background-color:White;
color:#15317E;
}
</style>
<asp:GridView ID="GridStudents" AutoGenerateColumns="false" GridLines="None" runat="server">
<RowStyle CssClass="GridViewRowStyle" />
<AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
<HeaderStyle CssClass="GridViewHeaderStyle" />
<Columns>
<asp:TemplateField HeaderText="Student">
<ItemTemplate>
<asp:label runat="server" ID="LblStudent" Text='<%# Bind("Student") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mark">
<ItemTemplate>
<asp:label runat="server" ID="LblMark" Text='<%# Bind("Mark") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image runat="server" ID="ImgSmiley" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(with sample-data):
Private Sub GridStudents_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridStudents.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim row = DirectCast(e.Row.DataItem, DataRowView)
Dim ImgSmiley = DirectCast(e.Row.FindControl("ImgSmiley"), Image)
Select Case DirectCast(row("Mark"), Int32)
Case Is < 50
ImgSmiley.ImageUrl = "~/Images/Smiley_Grim.png"
ImgSmiley.ToolTip = "bad"
Case Is < 70
ImgSmiley.ImageUrl = "~/Images/Smiley_Def.png"
ImgSmiley.ToolTip = "ok"
Case Else
ImgSmiley.ImageUrl = "~/Images/Smiley_Laugh.png"
ImgSmiley.ToolTip = "fine"
End Select
End Select
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
Dim tblStudent As New DataTable("Students")
Dim colStudent = New DataColumn("Student", GetType(String))
Dim colMark As New DataColumn("Mark", GetType(Int32))
tblStudent.Columns.Add(colStudent)
tblStudent.Columns.Add(colMark)
Dim newRow = tblStudent.NewRow
newRow("Student") = "Tom"
newRow("Mark") = 70
tblStudent.Rows.Add(newRow)
newRow = tblStudent.NewRow
newRow("Student") = "Bob"
newRow("Mark") = 40
tblStudent.Rows.Add(newRow)
newRow = tblStudent.NewRow
newRow("Student") = "Danny"
newRow("Mark") = 60
tblStudent.Rows.Add(newRow)
newRow = tblStudent.NewRow
newRow("Student") = "Sussie"
newRow("Mark") = 40
tblStudent.Rows.Add(newRow)
GridStudents.DataSource = tblStudent
GridStudents.DataBind()
End Sub