How to populate data from table to dropdown of gridview - asp.net

dropdown in gridview
<asp:TemplateField HeaderText="ProjectModifiedBy" HeaderStyle-BackColor="#C0C0C0" HeaderStyle-BorderColor="Black">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" Width="99%" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code of web method
<WebMethod()> _
Public Function BindDropDown() As SqlDataReader
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlQuery As String
sqlQuery = "Sp_SelectEmpName"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlQuery, con)
cmd.CommandType = CommandType.StoredProcedure
Dim reader As SqlDataReader
con.Open()
reader = cmd.ExecuteReader()
Return reader
End Function
this is the code behind method which calls webmethod,what should i write here to bind the empname column data with dropdown of gridview
Private Sub BindDataDropDown()
End Sub

Related

Display a list of images in a gridview from SQL

Using VS2013 (asp.net, VB) and SQL Server 2012.
I have a table in my database that consists of columns ID, Name and ProfilePic. ProfilePic has a type of image.
I want to display a list of ALL of the images in a gridview. Looking at google I can only find examples where someone is selecting an image based on an ID which is not what I want.
Here is my imageHandler.ashx:
<%# WebHandler Language="VB" Class="profilePICHandler" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Public Class profilePICHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("nefsaConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from ProfilePics"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("profilepic"), Byte()))
dReader.Close()
con.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
On my aspx page I have this
<asp:GridView ID="gridSelectAPic" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image runat="server"
ImageUrl='<%# "ProfilePICHandler.ashx"%>'
ID="profilePIC" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And on the code behind I have this
Dim dt As New DataTable
Dim conn As New SqlConnection(ConnectionString)
Using conn
Dim ad As New SqlDataAdapter("Select * from ProfilePics", conn)
ad.Fill(dt)
End Using
gridSelectAPic.DataSource = dt
gridSelectAPic.DataBind()
I am at a bit of a loss how to proceed so any help greatly appreciated
Its because your handler is implemented wrong. You will need a querystring to tell the handler which image you have to retrieve.
You can use asp:ImageField for brevity and readability. Markup
<asp:ImageField HeaderText="Image"
DataImageUrlField="EmployeeID"
DataImageUrlFormatString="ProfilePICHandler.ashx?id={0}" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image runat="server"
ImageUrl='<%# Eval("EmployeeID", "ProfilePICHandler.ashx?id={0}")%>'
ID="profilePIC" />
</ItemTemplate>
</asp:TemplateField>
Now fetch from querystring from the generic handler like this
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("nefsaConnectionString").ConnectionString
Dim cmd As New SqlCommand()
cmd.CommandText = String.Format("select profilepic from ProfilePics where EmployeeID=", context.Request.QueryString("id"))
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("profilepic"), Byte()))
dReader.Close()
con.Close()
End Sub
Please note that
I have given the name EmployeeID for your PK in DB
Your handler name is Pascalcased on Eval and CamelCased at its implementation. Is it a typo?
Haven't parameterized the query for brevity.

AutoCompleteExtender works fine on developing machine and it doesn't on pubblication server

Question tells all.
I got an AutoCompleteExtender that works as a clock on my pc running under VisualWebDeveloper's debug virtual machine but when I publish files on publication server it doesn't work...
This is the code i use in codebehind:
<System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod(EnableSession:=True)> Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager.ConnectionStrings("AFTERSALES").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "SELECT an_descr1, an_descr2 FROM anagrafica WHERE an_azienda = #azienda AND an_descr1 + ' ' + an_descr2 LIKE '%' + #SearchText + '%'"
cmd.Parameters.AddWithValue("#SearchText", prefixText)
cmd.Parameters.AddWithValue("#azienda", HttpContext.Current.Session("CODazienda").ToString)
cmd.Connection = conn
conn.Open()
Dim customers As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
customers.Add(Trim(sdr("an_descr1").ToString & " " & sdr("an_descr2").ToString))
End While
conn.Close()
conn = Nothing
Return customers
End Function
And here following are the controls i use in aspx search page (toolkitscriptmanager is in masterpage):
<asp:TextBox ID="TextBox1" runat="server" Width="300px" AutoPostBack="True"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServiceMethod="SearchCustomers"
MinimumPrefixLength="2" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" FirstRowSelected = "false"></ajaxToolkit:AutoCompleteExtender>

asp.net Auto complete textbox from database

I tried to make a text box which gives suggestions from database columns. However it's showing this error when i run that page .
Error -
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified.
asp code
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:AutoCompleteExtender ID="autoComplete1" runat="server"
EnableCaching="true"
BehaviorID="AutoCompleteEx"
MinimumPrefixLength="2"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
CompletionInterval="1000"
CompletionSetCount="20"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true"> </asp:AutoCompleteExtender>
<td><asp:TextBox ID="TextBox2" runat="server" CssClass="text_box" autocomplete="off"></asp:TextBox><br /><asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please Enter Client / Company Name" style="color:#f00; font-size:11px"></asp:RequiredFieldValidator></td>
vb code
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AutoComplete
Inherits System.Web.Services.WebService
Dim cn As New SqlClient.SqlConnection()
Dim ds As New DataSet
Dim dt As New DataTable
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, _
ByVal count As Integer) As String()
'ADO.Net
Dim strCn As String = _
"Data Source=SONAM-PC\SQLSERVER2008R2;Initial Catalog=Brandstik2; Integrated Security=True"
cn.ConnectionString = strCn
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cn
cmd.CommandType = CommandType.Text
'Compare String From Textbox(prefixText)
'AND String From Column in DataBase(CompanyName)
'If String from DataBase is equal to String from TextBox(prefixText)
'then add it to return ItemList
'-----I defined a parameter instead of passing value
'directly to prevent SQL injection--------'
cmd.CommandText = "select * from BrandstikTesti Where client_name like #myParameter"
cmd.Parameters.AddWithValue("#myParameter", "%" + prefixText + "%")
Try
cn.Open()
cmd.ExecuteNonQuery()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
Catch ex As Exception
Finally
cn.Close()
End Try
dt = ds.Tables(0)
'Then return List of string(txtItems) as result
Dim txtItems As New List(Of String)
Dim dbValues As String
For Each row As DataRow In dt.Rows
''String From DataBase(dbValues)
dbValues = row("client_name").ToString()
dbValues = dbValues.ToLower()
txtItems.Add(dbValues)
Next
Return txtItems.ToArray()
End Function
End Class
Add Top of your aspx page
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
Or You are missing dll

NullReferenceException when assigning dataset as datasource of dropdownlist

I want to assign datasource of a dropdownlist which is inside a gridview control. But when i am executing the following code i am getting NullReferenceException.
Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Try
Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
Dim Query As String = "select Course from Courses"
Dim Command As SqlCommand
Command = New SqlCommand(Query, Connection)
Dim Da As New SqlDataAdapter(Command)
Dim Ds As New DataSet()
Connection.Close()
Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
Da.Fill(Ds)
ddlCourse.DataSource = Ds //Exception is here
ddlCourse.DataTextField = "Course"
ddlCourse.DataValueField = "Id"
ddlCourse.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
You are closing the connection before filling the dataset and also you have not opened the connection so first open the connection then fill the dataset after that you can close the connection.
Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Try
Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
Dim Query As String = "select Course from Courses"
Dim Command As SqlCommand
Command = New SqlCommand(Query, Connection)
Dim Da As New SqlDataAdapter(Command)
Dim Ds As New DataSet()
Connection.Open()
Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
Da.Fill(Ds)
ddlCourse.DataSource = Ds //Exception is here
ddlCourse.DataTextField = "Course"
ddlCourse.DataValueField = "Id"
ddlCourse.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
Finally
Connection.Close()
End Try
End If
End Sub
Edit :
Add this line and run
If (ds.Tables.Count > 0) Then
//your binding code....
Else
MsgBox(ex.ToString)
End If
For reference
Link
Make sure your drop down is in the ItemTemplate section of the grid in your HTML code, you may have it in the edit section only ..
<asp:TemplateField HeaderText="Course">
<EditItemTemplate>
<asp:DropDownList ID="ddlCourse" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCourse" runat="server">
</asp:DropDownList>
<asp:Label ID="lblCourse" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Adding DataBound DropDownList to DataGrid

I have a DataGrid bound to a DataView which, among other columns has, an ID Column and ParentID Column, I need the user to be able to specify a ParentID using using a DropDownList (ComboBox).
Now, I have already added the DropDownList to the DataGrid like this:
<Columns>
[...]
<asp:TemplateColumn HeaderText="Parent" >
<ItemTemplate>
<asp:DropDownList ID="ddlParentID"
runat="server"
DataValueField="ID"
DataTextField="Short_Description"
Width="100%"
DataSource="<%# dsDV %> ">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
In the code-behind I have the following a method:
Protected dsDV As New DataView
Protected Sub PopulateDropDownList()
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString)
Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn)
comm.CommandType = CommandType.Text
Dim myTableTable As New DataTable
conn.Open()
myTableTable.Load(comm.ExecuteReader)
Me.dsDV = myTableTable.DefaultView
End Sub
That PopulateDropDownMethod is called on the form Load Event but, albeit DDLs do show, they show empty, as if no DataBinding is being made.
How can I properly bind the DDL with a dataSource in the codebehind? Or, if that's not the issue, how do I properly fill the DDL?
Update 1
After the first answer I went ahead and tried this (still no luck):
Protected Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgData.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList)
Me.PopulateDropDownList(ddl)
End If
End Sub
Protected dsDV As New DataView
Protected Sub PopulateDropDownList(ddl As DropDownList)
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString)
Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn)
comm.CommandType = CommandType.Text
Dim myTableTable As New DataTable
conn.Open()
myTableTable.Load(comm.ExecuteReader)
ddl.DataSource = myTableTable.DefaultView
ddl.DataBind()
End Sub
Note that I also removed the call to PopulateDropDownList from the Form Load Event handler.
you may try to call ddlParent.DataBind() after setting the datasource.
I don't why but taking the binding code from the aspx to the aspx.vb fixed the issue, so it all looks like this now:
<asp:TemplateColumn HeaderText="Parent" >
<ItemTemplate>
<asp:DropDownList ID="ddlParentID" runat="server" Width="100%" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
And for the code-behind, for each row:
Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList)
ddl.DataValueField = "ID"
ddl.DataTextField = "Short_Description"
ddl.DataSource = myTable.DefaultView
ddl.DataBind()

Resources