I am trying to an ImageUrl to an image in a Template Field in GridView but keep getting the error:
Object reference not set to an instance of an object. on this line:
Dim imagePath As String = rowView("image_path")
I've never done this before on a GridView but had it working on a ListView.
Thanks for any help heres my code:
.APSX
<asp:GridView ID="gvImages" DataKeyNames="id" runat="server" AutoGenerateColumns="False" BorderWidth="0px" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="imageId" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imageFile" runat="server"></asp:Image>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" />
</Columns>
</asp:GridView>
CODE BEHIND
Protected Sub gvImages_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvImages.RowDataBound
Dim rowView As DataRowView = CType(e.Row.DataItem, DataRowView)
Dim imagePath As String = rowView("image_path")
Dim strImageUrl As String = "~/admin/images/cases/" & Request.QueryString("uid") & "/" & imagePath
Dim imageFile As System.Web.UI.WebControls.Image = CType(e.Row.FindControl("imageFile"), System.Web.UI.WebControls.Image)
imageFile.ImageUrl = strImageUrl
End Sub
I think you need to check that its a data row and not the header row
Try this
Protected Sub gvImages_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvImages.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowView As DataRowView = CType(e.Row.DataItem, DataRowView)
Dim imagePath As String = rowView("image_path")
Dim strImageUrl As String = "~/admin/images/cases/" & Request.QueryString("uid") & "/" & imagePath
Dim imageFile As System.Web.UI.WebControls.Image = CType(e.Row.FindControl("imageFile"), System.Web.UI.WebControls.Image)
imageFile.ImageUrl = strImageUrl
End If
End Sub
try
Dim imagePath As String = e.rowView("image_path").ToString()
If the table binded with the grid has column "image_path", then instead use an easier way....
<asp:Image id="img1" runat="server" imageUrl = '<%#Eval("image_path")%>' />
If you want to build some custome string
imageurl = '<%# String.Format("{0} - {1} - {2} - {3}", Eval("Name1"), Eval("Name2"), Session["abc"],Request["abc"]) %>'
Related
Here is my problem. I have a user control that will download a binary file (image, pdf etc.) using a link button in gridview.
<asp:GridView Visible="true" ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"/>
<asp:BoundField DataField="FileName" HeaderText="File Name"/>
<asp:TemplateField HeaderText="Action" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" OnClick="DeleteFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
Protected Sub DownloadFile(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Dim bytes As Byte()
Dim fileName As String, contentType As String
Using con As New SqlConnection(DataSource.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "select FileName, PatImage, FileType from DB where Id=#Id"
cmd.Parameters.AddWithValue("#Id", id)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("PatImage"), Byte())
contentType = sdr("FileType").ToString()
fileName = sdr("FileName").ToString()
End Using
con.Close()
End Using
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
But this is not working if I have an UpdatePanel in my parent aspx page. So i googled and I found an answer; that is to place a code in RowDataBound:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim lb As LinkButton = TryCast(e.Row.FindControl("lnkDownload"), LinkButton )
ScriptManager.GetCurrent(Me.Page).RegisterAsyncPostBackControl(lb)
End Sub
And a new error occurred. That is I can't find my linkButton inside my GridView using my code in my RowDataBound.
So i googled again, and i found out that i should add a property to my aspx page ClientIDMode="AutoID". But this is only working on framework 4.x. And I couldn't do that 'cause im currently using 3.5. Are there any remedies in my current situation?
A already found an answer, I just changed my RowDataBound content, refer to the code:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim LButton = CType(e.Row.FindControl("lnkDownload"), System.Web.UI.WebControls.LinkButton)
Dim scriptManager__1 = ToolkitScriptManager.GetCurrent(Me.Page)
If scriptManager__1 IsNot Nothing Then
scriptManager__1.RegisterPostBackControl(LButton)
End If
End If
End Sub
I have this gridview in my application :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="Savebtn" runat="server" Text="تحديث البيانات" OnClick="gv_RowEditing"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="السعر الأقصى">
<ItemTemplate>
<asp:TextBox ID="mintxt" runat="server" Text='<%#Eval("prix max")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="السعر الأدنى" >
<ItemTemplate>
<asp:TextBox ID="maxtxt" runat="server" Text='<%#Eval("prix min")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Datvente" HeaderText="التاريخ" SortExpression="Datvente" />
<asp:BoundField DataField="NomAdh" HeaderText="الإسم و اللقب" SortExpression="NomAdh" />
<asp:BoundField DataField="CodAdh" HeaderText="المنخرط" SortExpression="CodAdh" />
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField ID="Ref" runat="server" Value='<%#Eval("Ref")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The event of the click into button :
Protected Sub gv_RowEditing(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim min As Double = Double.Parse(GridView1.SelectedRow.Cells("mintxt").ToString())
Dim max As Double = Double.Parse(GridView1.SelectedRow.Cells("maxtxt").ToString())
Dim reference As String = Double.Parse(GridView1.SelectedRow.Cells("Ref").ToString())
If min > max Then
avis2.Text = "الصيغة خاطئة"
Return
End If
DataAccessLayer.updatetraitementprix(min, max, reference)
avis2.Text = ""
FillingGrid(Session("region"), Session("date"), Session("speculation"))
Catch ex As Exception
avis2.Text = "الصيغة خاطئة"
GridView1.Visible = True
Return
End Try
Me.FillingGrid(Session("region"), Session("date"), Session("speculation"))
End Sub
I need to get the value of the column Ref and the new values of fields maxtxt and mintxt . but it didn't work
What are the reasons of this problem?
How can i resolve it?
There is absolutely need of RowEditing event. What you are doing is firing a simple OnClick event. So make these changes.
Markup ( Name change so that you may not confuse it with RowEditing event )
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="Savebtn" runat="server"
Text="تحديث البيانات"
OnClick="Savebtn_Click" />
</ItemTemplate>
</asp:TemplateField>
Code-behind
Protected Sub Savebtn_Click(sender As Object, e As System.EventArgs)
Dim btn As Button = CType(sender, Button)
Dim clickedRow As GridViewRow = CType(btn.NamingContainer, GridViewRow)
Dim minTextBox As TextBox = CType(clickedRow.FindControl("mintxt"), TextBox)
Dim maxTextBox As TextBox = CType(clickedRow.FindControl("maxtxt"), TextBox)
Dim refHidden As HiddenField = CType(clickedRow.FindControl("Ref"), HiddenField)
Dim min As Double = Double.Parse(minTextBox.Text)
Dim max As Double = Double.Parse(maxTextBox.Text)
Dim reference As Double = Double.Parse(refHidden.Value)
'rest of the code goes here
End Sub
Since the TextBox controls are inside of TemplateField's, you have to use Control#FindControl method to find them. Be aware of the Cell's index for each control.
Dim tbMin As TextBox = CType(GridView1.SelectedRow.Cells(1).FindControl("mintxt"), TextBox)
Dim min As Double = Double.Parse(tbMin.Text)
The reason you're getting this error is actually because the selectedrow is nothing, so you first need to get the current selected row then access all the controls in that row.
Please replace your code to the following:
Protected Sub gv_RowEditing(ByVal sender As Object, ByVal e As EventArgs)
Try
'First, get the saveBtn
Dim saveBtn As Button = DirectCast(sender, Button)
'Next, get the selected row of that button
Dim selectedRow As GridViewRow = DirectCast(saveBtn.Parent.Parent, GridViewRow)
'Now you can access all the controls of that row
Dim mintxt As TextBox = DirectCast(selectedRow.FindControl("mintxt"), TextBox)
Dim maxtxt As TextBox = DirectCast(selectedRow.FindControl("mintxt"), TextBox)
Dim Ref As HiddenField = DirectCast(selectedRow.FindControl("Ref"), HiddenField)
'Get the values of the controls
Dim min As Double = Double.Parse(mintxt.Text)
Dim max As Double = Double.Parse(maxtxt.Text)
Dim refVal As Double = Double.Parse(Ref.Value)
If min > max Then
avis2.Text = "الصيغة خاطئة"
Return
End If
DataAccessLayer.updatetraitementprix(min, max, refVal)
avis2.Text = ""
FillingGrid(Session("region"), Session("date"), Session("speculation"))
Catch ex As Exception
avis2.Text = "الصيغة خاطئة"
GridView1.Visible = True
Return
End Try
Me.FillingGrid(Session("region"), Session("date"), Session("speculation"))
End Sub
I have a gridview which accepts value from database table through textbox in it,then there are edit and save button.save button saves updates data to table. i want to add a button which will add new row with null values in textbox.please give me the method to add new row to grid view through generic collection list.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<br />
<asp:Button ID="Button1" runat="server" Text="Refresh" />
<br />
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ProjectId">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" readonly="true" Text='<%# Eval("Projectid") %>'>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectName">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="true" OnTextChanged="TextBox1_TextChanged" Text='<%# Eval("ProjectName") %>'
></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectModifiedDate">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" OnTextChanged="TextBox2_TextChanged" ReadOnly="true" Text='<%# Eval("ProjectmodifiedDate")%>' ></asp:TextBox>
<asp:Image ID="Image1" runat="server" Height="20px" Width="20px" ImageUrl="~/Images/calender.jpg"/>
<asp:CalendarExtender ID="CalendarExtender1" Enabled="false" TargetControlID="TextBox2" PopupButtonID="Image1" runat="server">
</asp:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RecordUpdatedDate">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" ReadOnly="true" Text='<%# Eval("recordupdateddate")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectLocation">
<ItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" OnTextChanged="TextBox5_TextChanged" ReadOnly="true" Text='<%# Eval("ProjectLocation")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LocationServerName">
<ItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" OnTextChanged="TextBox6_TextChanged" ReadOnly="true" Text='<%# Eval("LocationServerName")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectModifiedBy">
<ItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" OnTextChanged="TextBox7_TextChanged" ReadOnly="true" Text='<%# Eval("ProjectModifiedBy")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DBServer">
<ItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" OnTextChanged="TextBox8_TextChanged" ReadOnly="true" Text='<%# Eval("DBServer")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DBName">
<ItemTemplate>
<asp:TextBox ID="TextBox9" runat="server" OnTextChanged="TextBox9_TextChanged" ReadOnly="true" Text='<%# Eval("DBName")%>' > > </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
<asp:Button ID="Button4" runat="server" Text="Add New Row" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button3" runat="server" Text="Edit" />
<asp:Button ID="Button2" runat="server" Text="Save" Enabled="false"/>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
</form>
code behind
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class Projectinfo
Inherits System.Web.UI.Page
Shared projectinfolist As New List(Of projectinfoclass)
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim objtable As New DataTable("projectinfoclass")
Dim MyDS As DataSet
Dim Conn As SqlConnection
Dim Cmd As SqlDataAdapter
Conn = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
Cmd = New SqlDataAdapter("select * from ProjectInfoNew", Conn)
MyDS = New DataSet()
Cmd.Fill(objtable)
projectinfolist.Clear()
For Each dr As DataRow In objtable.Rows
projectinfolist.Add(New projectinfoclass With {.projectId = dr("Projectid").ToString(), .Projectname = dr("ProjectName").ToString(), .projectmodifiedDate = dr("ProjectmodifiedDate").ToString(), .ProjectLocation = dr("ProjectLocation").ToString(), .LocationServerName = dr("LocationServerName").ToString(), .ProjectModifiedBy = dr("ProjectModifiedBy").ToString(), .DBServer = dr("DBServer").ToString(), .DBName = dr("DBName").ToString()})
Next
GridView1.DataSource = objtable
GridView1.DataBind()
End Sub
Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
For Each obj In projectinfolist
If obj.Dirty = True Then
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlquery As String
sqlquery = "Sp_UpdateProjectInfo"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlquery, con)
cmd.CommandType = CommandType.StoredProcedure
Dim projectname As String = obj.Projectname
Dim projectmodifieddate As String = obj.projectmodifiedDate
Dim projectid As String = obj.projectId
Dim Recordupdateddate As String = obj.Recordupdateddate
Dim ProjectLocation As String = obj.ProjectLocation
Dim LocationServerName As String = obj.LocationServerName
Dim ProjectModifiedBy As String = obj.ProjectModifiedBy
Dim DBServer As String = obj.DBServer
Dim DBName As String = obj.DBName
cmd.Parameters.Add(New SqlParameter("#Projectid", SqlDbType.VarChar))
cmd.Parameters("#Projectid").Value = System.Convert.ToInt32(projectid)
cmd.Parameters.Add(New SqlParameter("#projectname", SqlDbType.VarChar))
cmd.Parameters("#projectname").Value = projectname
cmd.Parameters.Add(New SqlParameter("#projectmodifieddate", SqlDbType.VarChar))
cmd.Parameters("#projectmodifieddate").Value = projectmodifieddate
cmd.Parameters.Add(New SqlParameter("#ProjectLocation", SqlDbType.VarChar))
cmd.Parameters("#ProjectLocation").Value = ProjectLocation
cmd.Parameters.Add(New SqlParameter("#LocationServerName", SqlDbType.VarChar))
cmd.Parameters("#LocationServerName").Value = LocationServerName
cmd.Parameters.Add(New SqlParameter("#ProjectModifiedBy", SqlDbType.VarChar))
cmd.Parameters("#ProjectModifiedBy").Value = ProjectModifiedBy
cmd.Parameters.Add(New SqlParameter("#DBServer", SqlDbType.VarChar))
cmd.Parameters("#DBServer").Value = DBServer
cmd.Parameters.Add(New SqlParameter("#DBName", SqlDbType.VarChar))
cmd.Parameters("#DBName").Value = DBName
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Label1.Text = "Record inserted successfully"
con.Dispose()
End If
Next
Catch ex As Exception
Throw ex
Finally
End Try
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).Projectname = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).projectmodifiedDate = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox5_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).ProjectLocation = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox6_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).LocationServerName = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox7_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).ProjectModifiedBy = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox8_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).DBServer = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub TextBox9_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtbx As TextBox = TryCast(sender, TextBox)
Dim row As GridViewRow = txtbx.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectinfolist.Item(rowindex).DBName = txtbx.Text
projectinfolist.Item(rowindex).Dirty = True
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
For Each row As GridViewRow In GridView1.Rows
Dim tb1 As TextBox = DirectCast(row.FindControl("TextBox1"), TextBox)
tb1.ReadOnly = False
tb1.BorderColor = Drawing.Color.BurlyWood
Dim tb2 As TextBox = DirectCast(row.FindControl("TextBox2"), TextBox)
tb2.ReadOnly = False
tb2.BorderColor = Drawing.Color.BurlyWood
Dim cl As AjaxControlToolkit.CalendarExtender = DirectCast(row.FindControl("CalendarExtender1"), AjaxControlToolkit.CalendarExtender)
cl.Enabled = True
Dim tb5 As TextBox = DirectCast(row.FindControl("TextBox5"), TextBox)
tb5.ReadOnly = False
tb5.BorderColor = Drawing.Color.BurlyWood
Dim tb6 As TextBox = DirectCast(row.FindControl("TextBox6"), TextBox)
tb6.ReadOnly = False
tb6.BorderColor = Drawing.Color.BurlyWood
Dim tb7 As TextBox = DirectCast(row.FindControl("TextBox7"), TextBox)
tb7.ReadOnly = False
tb7.BorderColor = Drawing.Color.BurlyWood
Dim tb8 As TextBox = DirectCast(row.FindControl("TextBox8"), TextBox)
tb8.ReadOnly = False
tb8.BorderColor = Drawing.Color.BurlyWood
Dim tb9 As TextBox = DirectCast(row.FindControl("TextBox9"), TextBox)
tb9.ReadOnly = False
tb9.BorderColor = Drawing.Color.BurlyWood
Next
Button2.Enabled = True
End Sub
End Class
class
Imports Microsoft.VisualBasic
Public Class projectinfoclass
Public _Projectname As String
Public Property Projectname() As String
Get
Return _Projectname
End Get
Set(ByVal value As String)
_Projectname = value
End Set
End Property
Public _projectmodifiedDate As String
Public Property projectmodifiedDate() As String
Get
Return _projectmodifiedDate
End Get
Set(ByVal value As String)
_projectmodifiedDate = value
End Set
End Property
Public _projectid As String
Public Property projectId() As String
Get
Return _projectid
End Get
Set(ByVal value As String)
_projectid = value
End Set
End Property
Public _Recordupdateddate As String
Public Property Recordupdateddate() As String
Get
Return _Recordupdateddate
End Get
Set(ByVal value As String)
_Recordupdateddate = value
End Set
End Property
Public _ProjectLocation As String
Public Property ProjectLocation() As String
Get
Return _ProjectLocation
End Get
Set(ByVal value As String)
_ProjectLocation = value
End Set
End Property
Public _LocationServerName As String
Public Property LocationServerName() As String
Get
Return _LocationServerName
End Get
Set(ByVal value As String)
_LocationServerName = value
End Set
End Property
Public _ProjectModifiedBy As String
Public Property ProjectModifiedBy() As String
Get
Return _ProjectModifiedBy
End Get
Set(ByVal value As String)
_ProjectModifiedBy = value
End Set
End Property
Public _DBServer As String
Public Property DBServer() As String
Get
Return _DBServer
End Get
Set(ByVal value As String)
_DBServer = value
End Set
End Property
Public _DBName As String
Public Property DBName() As String
Get
Return _DBName
End Get
Set(ByVal value As String)
_DBName = value
End Set
End Property
Public _Dirty As Boolean
Public Property Dirty() As Boolean
Get
Return _Dirty
End Get
Set(ByVal value As Boolean)
_Dirty = value
End Set
End Property
End Class
I had a similar issue.... Wht i did was create a blank row in the table and bind it to the gridview, and put the last row in editmode!
This is really frustrating right now.
I have this hidden field on gridview markup:
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="dhide" Value='<%# Eval("shipDates","{0:M/dd/yyyy}") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then on codebehind, I am trying to retrieve the value of dhide:
Sub cancelIt_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim objConnection As SqlConnection
Dim DLdates As HiddenField = DirectCast(GridView1.FindControl("dhide"), HiddenField)
Response.write (DLdates)
What am I doing wrong?
The NamingContainer of it is not the GridView but the GridViewRow where it sits.
So:
For Each row As GridViewRow In GridView1.Rows
Dim dhide = DirectCast(row.FindControl("dhide"), HiddenField)
Dim shipDates = Date.ParseExact(dhide.Value, "M/dd/yyyy", Nothing)
' ...
Next
So what's happening is that I click the Edit button, type the updated values and hit Update. But the code-behind gets the original values not the updated values. I can't figure out why. It's always worked before.
Markup
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="7" ForeColor="#333333" GridLines="None" Font-Size="Small"
ShowFooter="True" DataKeyNames="CapID">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="AllocationId">
<ItemTemplate>
<asp:Label ID="show" runat="server" Text='<%# Eval("CapID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reference Number">
<ItemTemplate>
<asp:Label ID="showRefNo" runat="server" Text='<%# Eval("RefNo") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditRefNo"
Text='<%# Bind("RefNo") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertRefNo"
Text='<%# Bind("RefNo") %>'/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Resource">
<ItemTemplate>
<asp:Label ID="showResource" runat="server"
Text='<%# Eval("Resource") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditResource"
Text='<%# Bind("Resource") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertResource"
Text='<%# Bind("Resource") %>'/>
</FooterTemplate>
</asp:TemplateField>
<!-- and so on... -->
</Columns>
<!-- styles etc -->
<EmptyDataTemplate>
Ref Num: <asp:TextBox ID="newRefNo" runat="server"/>
Resource: <asp:TextBox ID="newResource" runat="server"/>
Hours Allocated: <asp:TextBox ID="newHours" runat="server"/>
Week Offset: <asp:TextBox ID="newOffset" runat="server"/>
<asp:Button runat="server" ID="NewDataInsert"
CommandName="NewDataInsert" Text="Insert"/>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Not IsPostBack Then
GridView1_DataBind()
GridView2_DataBind()
End If
End Sub
Protected Sub GridView2_RowUpdating(ByVal sender As Object, ByVal e As
GridViewUpdateEventArgs) Handles GridView2.RowUpdating
Dim capID As Label = GridView2.Rows(e.RowIndex).Cells(0)
.FindControl("show")
Dim refNo As TextBox = GridView2.Rows(e.RowIndex).Cells(1)
.FindControl("EditRefNo")
Dim resource As TextBox =
GridView2.Rows(e.RowIndex).Cells(2).FindControl("EditResource")
Dim hours As TextBox =
GridView2.Rows(e.RowIndex).Cells(3).FindControl("EditHours")
Dim offSet As TextBox =
GridView2.Rows(e.RowIndex).Cells(4).FindControl("EditOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim updateRows As DataRow() =
newResAlloc.Select("CapID = " & "'" & capID.Text & "'")
If (Not updateRows Is Nothing) And updateRows.Length > 0 Then
For Each updRow As DataRow In updateRows
updRow.BeginEdit()
updRow.Item("Refno") = refNo.Text
updRow.Item("Resource") = resource.Text
updRow.Item("Hours") = hours.Text
updRow.Item("Offset") = offSet.Text
updRow.EndEdit()
Next
End If
resourceInfo.updateResAllocations(newResAlloc)
GridView2.EditIndex = -1
GridView2_DataBind()
End Sub
This could be a million and one things. What have you checked? Have you narrowed it down?
Here's some starting points for you:
Put a breakpoint inside GridView2_RowUpdating to make sure it's being called.
Check the value of capID, or capID.Text - it shouldn't be 0.
Check that your database table contains a row where CapID equals the value of capID.Text
Put a breakpoint on updateRows to ensure that the database row is being loaded into your code.
Make sure that the updRow.EndEdit() is being hit, and that the values are populated into the row correctly.
Finally, check that the updateResAllocations is working properly. It's impossible to see from here how it works, so I can't give any advice on that.
The easiest way to fix this might be to ask whoever wrote it for some assistance.
The problem was that my RowCommand method was calling the DataBind
Wrong way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
End If
GridView2_DataBind() 'Culprit
End Sub
Right way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
End If
End Sub