This is in vb.net
The photo never show up and I have no error....???
This is how I stock the photo on The SQl DB
Sub StartUpLoad()
Dim imgName As String = FileUpload1.FileName
Dim imgSize As Int32 = FileUpload1.PostedFile.ContentLength
Dim photo As Byte() = New Byte(imgSize) {}
Dim user As String = "kdjhkjgh"
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName IsNot "" Then
If (FileUpload1.PostedFile.ContentLength > 100240) Then
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "alert depuis le codehind", String.Format("alert('{0}')", "Fichier trop gros"), True)
Else
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("dbo.addPost", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = user
cmd.Parameters.Add("#titre", SqlDbType.NVarChar).Value = TextBoxTitre.Text
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value = TextBoxDescrip.Text
cmd.Parameters.Add("#image", SqlDbType.Image).Value = photo
cmd.ExecuteNonQuery()
con.Close()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "alert depuis le codehind", String.Format("alert('{0}')", "Post sauvegardé"), True)
End If
End If
End Sub
This my handler
Public Class Handler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select Titre,Image from Post where ID =#IID"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ImageID As New SqlParameter("#IID", Data.SqlDbType.Int)
ImageID.Value = Convert.ToInt32(context.Request.QueryString("ID"))
cmd.Parameters.Add(ImageID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("Image"), 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
This is my asp data grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Titre" HeaderText="Titre" SortExpression="Titre" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>
</ItemTemplate>
<ControlStyle Height="200px" />
</asp:TemplateField>
<asp:ImageField DataImageUrlField="Image">
</asp:ImageField>
</Columns>
</asp:GridView>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BecsEtMuseauxSQL %>"
ProviderName="<%$ ConnectionStrings:BecsEtMuseauxSQL.ProviderName %>" SelectCommand="SELECT [ID], [Titre], [Image] FROM [Post]"></asp:SqlDataSource>
Do you have any idea why my photo never show up???
Thanks for helping me!!!
I think, you response doesn't know what type of binary data you are sending (by default it is text/html). Try to set ContentType to "image/jpeg" (exactly, there must be your image file MIME).
If you download different image types it is better to store into table Post its MIME in your addPost procedure (you may use FileUpload1.PostedFile.ContentType property for this purpose) and use it in handler.
you can use context.Response.ContentType property to mention file details, so that browser can serve basic needs to rendering.
context.Response.ContentType=ImageFormat.Jpeg;
Related
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.
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
I have a comments box which has a template field which looks something like this..
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="CommentsDataSource" Height="167px" Width="325px">
<Columns>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<div style="background-color:Silver">
<div class="avatar-frame">
<asp:Image ID="ProfilePic" runat="server"/>
</div>
<h1><%# Eval("TagLine")%></h1>
<h2><%# Eval("IfNonMemberUserName")%></h2>
<p><%# Eval("CommentBody")%></p>
</div>
</ItemTemplate>
<AlternatingItemTemplate>
<div style="background-color:White">
<div class="avatar-frame">
</div>
<h1><%# Eval("TagLine")%></h1>
<h2><%# Eval("IfNonMemberUserName")%></h2>
<p><%# Eval("CommentBody")%></p>
</div>
</AlternatingItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="CommentsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:BookMeetConnString %>" ProviderName="<%$ ConnectionStrings:BookMeetConnString.ProviderName %>" SelectCommand="SELECT [IfNonMemberUserName], [UserAvatar], [TagLine], [CommentBody] FROM [comments] WHERE ([BookID] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="?" QueryStringField="ID" />
</SelectParameters>
</asp:SqlDataSource>
Some background:
I have an MS Access database with a table called 'userprofiles' which has a field called AvatarURL. Similiarly there is also a table called 'comments' which has lookupfield called 'UserAvatar' inside of it referring to the 'userprofiles' table's 'AvatarURL' field.
I am receiving the "'ProfilePic' is not declared. It may not be accessible due to it's permission level" error in my code behind. Intellisense is telling me that the image that has the ID 'ProfilePic' is not declared (within the DisplayData sub routine.
The problematic bit of code is:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
conn.Close()
End Sub
At runtime, detail.aspx works fine, but the avatars in the comment box don't show up at all. What am I doing wrong?
EDIT:
I have managed to get this far:
Protected Sub GridView2_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim ProfilePic
If e.Row.RowType = DataControlRowType.DataRow Then
ProfilePic = e.Row.FindControl("ProfilePic")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
End If
conn.Close()
End Sub
However, the images still do not appear at runtime. What is wrong with this? Should I be using the datareader?
The only way to refer to get at ProfilePic is to set it at DataBind time. You'll need to wire up the GridView2_RowDataBound event by adding OnRowDataBound="GridView2_RowDataBound" to your asp:GridView tag.
You'll then get the RowDataBound event for each row (even header and footer rows, so you need to test for what type of row is currently firing the event. You can then use FindControl on the current row item to look for the current row's ProfilePic. You'll have to cast the output of that function into an Image.
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image ProfilePic = (Image)e.Row.FindControl("ProfilePic");
ProfilePic.ImageUrl = "stuff";
}
}
As a control within a template, you can only access the control when binding, in particular in the OnRowDataBound event handler (for a GridView).
In this event handler you need to call FindControl with the ID of the wanted control and cast it to the right type (only if you need to access specific members of that type).
Try this
public string DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
string imagename= profileDr("AvatarURL")
conn.Close()
return imagename
End Sub
and client side change for
<asp:Image ID="ProfilePic" **ImageUrl='<%# DisplayData()%>'** runat="server" />
I have my GridView populating like so:
<asp:Panel ID="pnlGrid" runat="server">
<div class="m_container" style="margin-bottom:20px;">
<asp:GridView ID="grdView" runat="server" CssClass="GridViewStyle"
AutoGenerateColumns="False" GridLines="None" Width="125%" onrowdatabound="builderGridView_RowDataBound" >
<Columns>
<asp:BoundField DataField="id" Visible="False" />
<asp:BoundField HeaderText="Info" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton name='<%#Eval("status") %>' CommandArgument='<%#Eval("id")%>' runat="server" Text='<%#Eval("status")%>' CommandName='<%#Eval("status")%>' ID="statusLink" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="RowS" />
<EmptyDataRowStyle CssClass="EmptyS" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedS" />
<HeaderStyle CssClass="HeaderS" />
<EditRowStyle CssClass="EditRowS" />
<AlternatingRowStyle CssClass="AltRowS" />
</asp:GridView>
</div>
</asp:Panel>
</asp:Content>
And the code behind is:
Private Sub LoadData(ByRef theStatus As Integer)
Dim objConn As MySqlConnection
Dim objCmd As MySqlCommand
objConn = New MySqlConnection(strConnString)
objConn.Open()
Dim strSQL As String
strSQL = "SELECT * FROM theTable WHERE status=" & theStatus & " ORDER BY created_on, status DESC;"
Dim dtReader As MySqlDataReader
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
grdView.DataSource = dtReader
grdView.DataBind()
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End Sub
Then after the above i create a LinkButton for each row like so:
Sub builderGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lbtn As LinkButton = DirectCast(e.Row.FindControl("statusLink"), LinkButton)
e.Row.Cells(1).Text = "TEST!"
If lbtn.Text = 0 Then
Dim lb As New LinkButton()
lb.Text = "Accept"
lb.CommandName = lbtn.CommandName
lb.CommandArgument = lbtn.CommandArgument
lb.Attributes.Add("class", "nounderline")
lb.ForeColor = System.Drawing.Color.Green
lb.Font.Bold = True
lb.Font.Size = 12
lb.OnClientClick = "location.href = '/page.aspx?ID=" & pageID & "&dbid=" & lb.CommandArgument & "&ACCEPT=yes'; return false;"
e.Row.Cells(4).Controls.Add(lb)
End If
End If
End Sub
How can i get values from the database (name, address, email address, etc etc) and place it within the current row its going through?
example:
(when its looping through the rows)
e.Row.Cells(1).Text = database("FName") & "<BR />" & database("LName") & "<BR />"...etc etc
Would look like this in the first row column:
Bob
Barker
How can i grab whats currently being read from the DB?
builderGridView_RowDataBound event fill be handled for each row from the database.
e.Row.DataItem will contain the item from the database
Edit:
Better way would be
Using adap As New MySqlDataAdapter(objCmd)
Dim table As New DataTable()
adap.Fill(table)
grdView.DataSource = table;
grdview.DataBind();
Adapter will load all records to the DataTable.
Then your e.Row.DataItem will be of type DataRow
I'm running into a little problem with a gridview and a dropdownlist. I can get the dropdownlist to load initially, but when it autopostback's it returns with no value. I am populating the dropdownlist in the RowEditing sub. I'm guessing that I must somehow rebind in the RowDataBound sub, but don't know how to go about it. If I try to find the control's SelectedValue I end up with nothing.
VB Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
bindGridView()
End If
End Sub
'Menu Click
'bindGridView
Public Sub bindGridView(Optional ByVal sortExp As String = "", Optional ByVal sortDir As String = "")
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
If sortExp <> String.Empty Then
sortExp = (sortExp & " " & sortDir).ToString
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber ORDER BY " & _
"#sortExp"
cmd.Parameters.AddWithValue("sortExp", sortExp)
Else
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber"
End If
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
gvProgramDetails.DataSource = myDataSet
gvProgramDetails.DataBind()
End Sub
'ProgramDetails Load
Protected Sub gvProgramDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProgramDetails.Load
bindGridView()
End Sub
'ProgramDetails Paging
Protected Sub gvProgramDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvProgramDetails.PageIndexChanging
gvProgramDetails.PageIndex = e.NewPageIndex
bindGridView()
End Sub
'ProgramDetails Sorting
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
Dim SortDirection As String
If Session("SortDirection") = vbNullString Then
Session("SortDirection") = "DESC"
Else
SortDirection = Session("SortDirection").ToString
If SortDirection = "ASC" Then
SortDirection = "DESC"
ElseIf SortDirection = "DESC" Then
SortDirection = "ASC"
Else
SortDirection = "ASC"
End If
bindGridView(e.SortExpression, Session("SortDirection"))
'Need to store sort info in view state
Session("SortDirection") = SortDirection
End If
End Sub
'ProgramDetails RowEditing
Protected Sub gvProgramDetails_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvProgramDetails.RowEditing
Dim lbl As Label = CType(gvProgramDetails.Rows(e.NewEditIndex).FindControl("lblRecordType"), Label)
Dim strValue As String = lbl.Text
gvProgramDetails.EditIndex = e.NewEditIndex
bindGridView()
Dim row As GridViewRow = gvProgramDetails.Rows(e.NewEditIndex)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("CSPaperWEBConnectionString").ConnectionString
Dim ddlRecordType As DropDownList = CType(row.FindControl("ddlRecordType"), DropDownList)
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
sql = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
If ddlRecordType IsNot Nothing Then
ddlRecordType.DataTextField = "RecordType"
ddlRecordType.DataValueField = "RecordType"
ddlRecordType.DataSource = myDataSet
ddlRecordType.SelectedValue = strValue
ddlRecordType.DataBind()
End If
End Sub
Protected Sub gvProgramDetails_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvProgramDetails.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ctrl As Control = e.Row.FindControl("ddlRecordType")
If ctrl IsNot Nothing Then
Dim ddlRecordType As DropDownList = ctrl
MsgBox(ddlRecordType.SelectedValue)
End If
End If
End Sub
'ProgramDetails RowUpdating
Protected Sub gvProgramDetails_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvProgramDetails.RowUpdating
Dim ddlRecordType As DropDownList = gvProgramDetails.Rows(e.RowIndex).FindControl("ddlRecordType")
MsgBox(ddlRecordType.SelectedValue)
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowCancelingEdit
Protected Sub gvProgramDetails_RowCancelingEdit1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gvProgramDetails.RowCancelingEdit
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowDeleting
Protected Sub gvProgramDetails_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvProgramDetails.RowDeleting
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String = "delete from tblPrgTrackProgramDocumentation where ProgramNumber = #ProgramNumber and RecordType = #RecordType and ProgramInformation = #ProgramInformation"
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandText = sql
cmd.Parameters.AddWithValue("ProgramNumber", strProgramNumber)
cmd.Parameters.AddWithValue("RecordType", strRecordType)
cmd.Parameters.AddWithValue("ProgramInformation", strProgramInformation)
cmd.ExecuteNonQuery()
cmd.Dispose()
bindGridView()
End Sub
ASP front end
<ajx:UpdatePanel ID="ajaxpanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False"
CssClass="gridview" DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="3" AllowSorting="True" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<ControlStyle CssClass="button delete" />
</asp:TemplateField>
<asp:CommandField ControlStyle-CssClass="button save" ShowEditButton="True">
<ControlStyle CssClass="button save" />
</asp:CommandField>
<asp:BoundField DataField="ProgramNumber" HeaderText="ProgramNumber"
InsertVisible="False" ReadOnly="True" SortExpression="ProgramNumber" />
<asp:BoundField DataField="ProgramName" HeaderText="ProgramName" ReadOnly="True"
SortExpression="ProgramName" />
<asp:BoundField DataField="ProgramStatus" HeaderText="ProgramStatus" ReadOnly="True"
SortExpression="ProgramStatus" />
<asp:TemplateField HeaderText="RecordType" SortExpression="RecordType">
<EditItemTemplate>
<asp:DropDownList ID="ddlRecordType" runat="server" autopostback="True">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRecordType" runat="server" Text='<%# Bind("RecordType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProgramInformation" HeaderText="ProgramInformation"
SortExpression="ProgramInformation" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:WEBConnectionString %>"
SelectCommand="SELECT * FROM [tblPrgTrackValidRecordTypes]"></asp:SqlDataSource>
</ContentTemplate>
</ajx:UpdatePanel>
For those of you who answer drag the control in from the toolbox, create datasource, and set bind("RecordType") please don't. I've tried it that way and the value would always post back with whatever Recordtype was. So unless if you can solve that version of this gridview don't use drag/drop control solution. I'm scratching my brain to solve this one.
Update
I created under App_Code Process/ddlRecordType.vb
Imports Microsoft.VisualBasic
Namespace processes.ProgramTrack.dllRecordType
Public Class ddlRecordType
Public Sub ddlRecordType()
End Sub
Public Function GetRecords() As DataSet
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString.ToString
cmd.CommandText = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.Connection = conn
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.Fill(myDataSet)
Return myDataSet
End Function
End Class
End Namespace
My markup then looks like this.
<asp:DropDownList ID="ddlRecordType" DatasourceID="odsRecordType" DataTextField="RecordType" DataValueField="RecordType" runat="server" autopostback="True" > </asp:DropDownList>
<asp:ObjectDataSource ID="odsRecordType" runat="server" TypeName="processes.ProgramTrack.dllRecordType.ddlRecordType" SelectMethod="GetRecords"></asp:ObjectDataSource>
Then I get the same problem as before about the DDL not maintaining it's value at postback. Should I start a new Question or continue with this one?
Update to fix the DDL not maintaining. Disable Viewstate for the gridview.
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False" CssClass="gridview"DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="10" EnableViewState="False" AllowSorting="True">
Try creating an objectDataSource for the DDL, and use that. The problem is that the DDL has to be initialized at page load, or on page init, OR via a DataSource control. If you weren't using the Ajax UpdatePanel (go ahead, take it out, watch your code work, it should anyways) then you would be able to do it like this.
If you'll introduce an ObjectDataSource (and you can pass parameters to it too) then you should end up with what you want.
Edit:
I'm going to provide code from a project of mine, so that you can see how I'm using it. This code will not be perfect to your needs, but will show you how to do what you want.
namespace Appropriate.Namespace.Here {
public class MyType {
public List<KeyValuePair<string, string>> GetRoles() {
List<KeyValuePair<string, string>> l = new List<KeyValuePair<string, string>>();
l.Add( new KeyValuePair<string, string>( "Level1", "Analyst" ) );
l.Add( new KeyValuePair<string, string>( "Level2", "Customer Service" ) );
l.Add( new KeyValuePair<string, string>( "Level3", "Customer Service Manager" ) );
l.Add( new KeyValuePair<string, string>( "Level4", "Full-Access User" ) );
l.Add( new KeyValuePair<string, string>( "Level5", "Super User" ) );
return l;
}
}
}
<asp:DropDownList ID="cmbRoles" runat="server" AutoPostBack="False" DataSourceID="odsRoles" DataTextField="Value" DataValueField="Key" />
<asp:ObjectDataSource ID="odsRoles" runat="server" TypeName="Appropriate.Namespace.Here.MyType" SelectMethod="GetRoles" />
Notice how the namespace and typename work together to give me the SelectMethod? I'm not providing an override on the select parameters, altho you could. You would do that in the page backing code, and I could give some insight on that as well, but I'm trying to not be entirely overly complex.
Notice how I'm returning a List from the method? And I'm just defining it in that method? You could just as easily do a database call there.