I'm using Visual Studio 2005 and ASP. NET 2.0 with this program. This is written in VB.net
Right now, we've got a Gridview that is embedded and databound into another gridview. The 2nd Gridview is hidden by default and expanded by the user. Within the 2nd gridview are several DropDownLists. The problem is that these DropDownLists are not firing the OnSelectedIndexChanged functon nor AutoPostback whenever I change the selecteditem.
I'm curious as to why it is not firing. Thank you.
Gridview1:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
Dim strCNRNum As String
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
' Find Child GridView control
Dim gv As GridView = New GridView()
gv = row.FindControl("GridView2")
If gv.UniqueID = gvUniqueID Then
gv.EditIndex = gvEditIndex
ClientScript.RegisterStartupScript(GetType(Page), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + e.Row.DataItem("CNR_NUM").ToString() & "','one');</script>")
End If
' Prepare the query for Child GridView by passing
' the Customer ID of the parent row
'Dim dsTemp As SqlDataSource
'dsTemp = ChildDataSource(e.Row.DataItem("CNR_NUM").ToString, strSort)
'gv.DataSource = dsTemp
'gv.DataBind()
strCNRNum = e.Row.DataItem("CNR_NUM").ToString()
Dim dt As DataTable = New DataTable()
Dim con As SqlConnection = New SqlConnection(ConnectionString)
Try
con.Open()
Dim strSQL As String
strSQL = "select " & _
"CS.SID, " & _
"CS.CNR_NUM, " & _
"CS.STEP_NUM, " & _
"CS.SERVER_ID, " & _
"S.SERVER_NM, " & _
"CS.DATABASE_ID, " & _
"D.DATABASE_NM, " & _
"CS.CMD_FILE_NM, " & _
"CS.EXECUTE_DTTM, " & _
"CS.STEP_TYPE_ID, " & _
"ST.STEP_TYPE, " & _
"ISNULL(CS.LOG_FILE_NM,'') as LOG_FILE_NM " & _
"from " & _
"dbo.CNR_STEPS CS INNER JOIN dbo.CNR_SERVERS S on CS.SERVER_ID = S.SERVER_ID " & _
"INNER JOIN dbo.CNR_DATABASES D ON CS.DATABASE_ID = D.DATABASE_ID " & _
"INNER JOIN dbo.CNR_STEP_TYPES ST ON CS.STEP_TYPE_ID = ST.STEP_TYPE_ID " & _
"where " & _
"CS.CNR_NUM = '" & strCNRNum & "' " & _
"order by " & _
"CS.STEP_NUM"
Dim cmd As SqlCommand = New SqlCommand(strSQL, con)
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
da.Fill(dt)
If dt.Rows.Count > 0 Then
gv.DataSource = dt
gv.DataBind()
Else
dt.Rows.Add(dt.NewRow())
dt.Rows(0)("CNR_NUM") = strCNRNum
dt.Rows(0)("LOG_FILE_NM") = ""
gv.DataSource = dt
gv.DataBind()
Dim colCount As Integer = gv.Columns.Count
gv.Rows(0).Cells.Clear()
gv.Rows(0).Cells.Add(New TableCell())
gv.Rows(0).Cells(0).ColumnSpan = colCount
gv.Rows(0).Cells(0).HorizontalAlign = HorizontalAlign.Center
gv.Rows(0).Cells(0).ForeColor = System.Drawing.Color.Red
gv.Rows(0).Cells(0).Font.Bold = True
gv.Rows(0).Cells(0).Text = "No Steps Defined"
End If
Catch ex As Exception
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Text = "Error: " & ex.Message.ToString()
'ClientScript.RegisterStartupScript(GetType(Page), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>")
End Try
End Sub
ASP code for the 2nd gridview, which is within the first one:
<asp:GridView ID="GridView2" AllowPaging="True" AllowSorting="true" Width="100%" Font-Size="Small" AutoGenerateColumns="false" runat="server" DataKeyNames="CNR_NUM" ShowFooter="true" OnRowEditing = "GridView2_RowEditing"
OnRowCommand = "GridView2_RowCommand"
OnRowDeleting = "GridView2_RowDeleting"
OnRowDeleted = "GridView2_RowDeleted"
OnRowUpdating = "GridView2_RowUpdating"
OnRowUpdated = "GridView2_RowUpdated"
OnRowCancelingEdit = "GridView2_CancelingEdit"
OnRowDatabound="GridView2_RowDataBound"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
>
<HeaderStyle Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Step Type">
<ItemTemplate><%#Eval("STEP_TYPE")%></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_StepTypes"
DataSourceID="ds_StepTypes"
SelectedValue='<%# Eval("STEP_TYPE_ID")%>'
DataTextField="STEP_TYPE"
DataValueField="STEP_TYPE_ID"
runat="server"
Width="100px"
Font-Size="X-Small"
AutoPostBack="true"
OnSelectedIndexChanged = "ddl_StepTypes_SelectedIndexChanged">
</asp:DropDownList>
<label id="lblTest"></label>
<!--<asp:TextBox ID="txtStepType" Text='<%# Eval("SERVER_ID")%>' runat="server"></asp:TextBox>-->
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList DataSourceID="ds_StepTypes"
DataTextField="STEP_TYPE" DataValueField="STEP_TYPE_ID" ID="ddl_StepTypes" runat="server" Width="100px" Font-Size="X-Small"></asp:DropDownList>
<!--<asp:TextBox ID="txtStepType" Text='' runat="server"></asp:TextBox>-->
</FooterTemplate>
</asp:TemplateField>
If any more information is needed, please let me know. Thank you.
The problem is that if you add a control to a template, the GridView creates multiple copies of that control, one for each data item. When the item is chosen, you need a way to determine which Dropdownlist was clicked and which row it belongs to.
The way to resolve this problem is to use an event from the GridView.
The GridView.RowCommand event serves this purpose. Unfortunately initially it is supposed to fire whenever any button is clicked in any template. This process, where a control event in a template is turned into an event in the containing control, is called event bubbling.
May be a workaround described here can help you. Alternatively may be this article could also help (or another one referenced at the very bottom).
Related
I have an ASP search style form that connects to a SQL database. I have figured out the code using SQL and I have been trying to add it to my ASP form. Everything I have tried just gives me the error "A field or property with the name 'A.FirstNameFirst' was not found on the selected data source".
Here is my front code:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" Style="text-align: center" PageSize="2" Width="840px" ForeColor="#333333" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="A.FirstNameFirst" HeaderText="Full Name" HeaderStyle-BackColor="#99CCFF" />
<asp:BoundField DataField="B.ServiceLocation" HeaderText="Address" HeaderStyle-BackColor="#99CCFF" />
<asp:BoundField DataField="C.out_trans_dt" HeaderText="Bill Due Date" HeaderStyle-BackColor="#99CCFF" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString2 %>"></asp:SqlDataSource>
Here is my behind code:
Dim fnameSearchID, lnameSearchID, addressSearchID As TextBox
Dim searchItem As Boolean = False
Dim searchString As String
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Try
searchString = "SELECT A.FirstNameFirst AS 'Name', B.ServiceLocation AS 'Location', MAX(C.out_trans_dt) AS 'Bill Paid' From [database].[dbo].[vw_Simple_customer] AS A JOIN [database].[dbo].[vw_location] AS B ON B.customer_id=A.customer_id JOIN [database].[dbo].[ub_financial_tran_detail] AS C ON C.location_id=B.location_id"
fnameSearchID = CType(DetailsView1.FindControl("fnameSearchID"), TextBox)
lnameSearchID = CType(DetailsView1.FindControl("lnameSearchID"), TextBox)
addressSearchID = CType(DetailsView1.FindControl("addressSearchID"), TextBox)
If String.IsNullOrEmpty(fnameSearchID.Text) = False Then
searchString += " WHERE A.FirstName LIKE '%" + fnameSearchID.Text + "%'"
searchItem = True
End If
If String.IsNullOrEmpty(lnameSearchID.Text) = False Then
If searchItem Then
searchString += " AND A.Surname LIKE '%" + lnameSearchID.Text + "%'"
Else
searchString += " WHERE A.Surname LIKE '%" + lnameSearchID.Text + "%'"
searchItem = True
End If
End If
If String.IsNullOrEmpty(addressSearchID.Text) = False Then
If searchItem Then
searchString += " AND B.ServiceLocation LIKE '%" + addressSearchID.Text + "%'"
Else
searchString += " WHERE B.ServiceLocation LIKE '%" + addressSearchID.Text + "%'"
searchItem = True
End If
End If
searchString += " GROUP BY ServiceLocation, FirstNameFirst"
Dim aSqlDataReader As SqlDataReader
Dim aSqlConnection As SqlConnection = New SqlConnection("Server=apphost007;Initial Catalog=database;User ID=user;Password=password")
Dim aSqlCommand As SqlCommand = New SqlCommand(searchString, aSqlConnection)
aSqlConnection.Open()
aSqlDataReader = aSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
'Fill gridview with search results
GridView1.DataSource = aSqlDataReader
GridView1.AutoGenerateColumns = False
GridView1.DataBind()
'set fields read only
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly)
searchCriteria.Visible = False
searchResults.Visible = True
Catch ex As Exception
Response.Write("*** UNABLE TO SUBMIT SEARCH.*** " & ex.Message)
End Try
End Sub
Please let me know if you can see the error.
This is supposed to be easy. I have done it successfully a ton of times.
I select an option from drodpwonlist1 and the second dropdownlist gets populated based on select fro dropdownlist1.
For some reason, the code below is not working.
Please have a look at simplified version of the code:
'//markup:
<div class="ui-widget">
<asp:DropDownList ID="ddlUsers" runat="server" placeholder="Select a user..." AppendDataBoundItems="True" Width="300px" OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged">
<asp:ListItem Value=""></asp:ListItem>
</asp:DropDownList>
</div>
<br /><br />
<div class="ui-widget">
<asp:DropDownList ID="ddlDates" runat="server" Enabled = "false" placeholder="Select a date..." Width="300px">
<asp:ListItem Value=""></asp:ListItem>
</asp:DropDownList>
</div>
'//Code behind:
Public Sub PopulateUsers()
Dim cmd As New SqlCommand("select DISTINCT c.userid,c.userName from tblUsers c " & _
"Inner Join tblInstructors i on c.instructorId = i.instructorId " & _
"ORDER BY c.userName ASC", New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
ddlUsers.DataSource = ddlValues
ddlUsers.DataValueField = "userId"
ddlUsers.DataTextField = "userName"
ddlUsers.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
Protected Sub ddlUsers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
ddlDates.Items.Clear()
ddlDates.Items.Add(New ListItem("--Select a date--", ""))
ddlDates.AppendDataBoundItems = True
Dim strConnString As [String] = ConfigurationManager _
.ConnectionStrings("DBConnectionString").ConnectionString
Dim strQuery As [String] = "select DISTINCT d.dateId, d.TrainingDates from tblTrainingDates d " & _
"Inner Join tblCourses c on d.dateid=c.dateid " & _
"WHERE c.userId = #userId ORDER BY d.TrainingDates ASC"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Parameters.AddWithValue("#userId", _
ddlUsers.SelectedItem.Value)
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
ddlDates.DataSource = cmd.ExecuteReader()
ddlDates.DataTextField = "dateId"
ddlDates.DataValueField = "TrainingDates"
ddlDates.DataBind()
If ddlDates.Items.Count > 1 Then
ddlDates.Enabled = True
Else
ddlDates.Enabled = False
End If
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
If there is a match between userid from first dropdownlist and second dropdownlist, enable second dropdownlist and populate related values.
The second dropdownlist is not getting enabled, neither are associated values getting populated.
Any ideas what I could be doing wrong?
The code is not working becouse you forget the AutoPostback=True
<asp:DropDownList ID="ddlUsers" runat="server" placeholder="Select a user..." AppendDataBoundItems="True" Width="300px" OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged" AutoPostback="True">
<asp:ListItem Value=""></asp:ListItem>
</asp:DropDownList>
Wihtout that the event OnSelectedIndexChanged never will fire.
I have problem regarding child gridview (gridview inside ListView), so far i solved the databind and the the Delete command , but i couldn't figure out the Edut Mode ( i click the image button) but the GV doesn't go to edit mode the codes are as follows: thanks in advance
Page mark-up:
EditItemTemplate
<asp:ImageButton ID="imgbUpdate" runat="server" CommandName="Update" Text="Update" ImageUrl="~/Images/save_icon_mono.gif" CausesValidation="true" ValidationGroup="vgrpSaveContact"/>
<asp:ImageButton ID="imgbCancel" runat="server" CommandName="Cancel" Text="Cancel" ImageUrl="~/Images/undo_icon_mono.gif" CausesValidation="false"/>
EditItemTemplate
<ItemTemplate>
<table>
<tr>
<td> <asp:ImageButton ID="imgbEdit" runat="server" CommandName="Edit" Text="Edit" ImageUrl="~/Images/edit_icon_mono.gif" />
</td>
<td> <asp:ImageButton ID="imgbDelete" runat="server" CommandName="Delete" Text="Delete" ImageUrl="~/Images/delete_icon_mono.gif" ToolTip="Delete"/>
</td>
</tr>
</table>
</ItemTemplate>
Code VB.NET
Protected Sub gvSorties_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim gvTemp As GridView = DirectCast(sender, GridView)
gvUniqueID = gvTemp.UniqueID
'Get the value
Dim strSortieID As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("lblSortieID"), Label).Text
Using conn As New SqlConnection
conn.ConnectionString = connString
conn.Open()
Try
Dim strSQL As String = ""
Dim dsTemp As New SqlDataSource()
dsTemp.ConnectionString = connString
'Get the values stored in the text boxes
Dim strMissionNo As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtMissionNo"), TextBox).Text
Dim strCaptain As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtCaptain"), TextBox).Text
Dim strCrew As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtCrew"), TextBox).Text
Dim strFuel As String = DirectCast(gvTemp.Rows(e.RowIndex).FindControl("txtFuel"), TextBox).Text
'Prepare the Update Command of the DataSource control
strSQL = "UPDATE Sortie set MissionNo = '" & strMissionNo & "'" & ",Captain = " & strCaptain & "" & ",Crew = '" & strCrew & "'" & ",Fuel = '" & strFuel & "'" & " WHERE SortieID = " & strSortieID
dsTemp.UpdateCommand = strSQL
dsTemp.Update()
'Reset Edit Index
gvEditIndex = -1
lvODV.DataBind()
conn.Close()
Catch
End Try
End Using
End Sub
Many thanks to every one
I have declared variables and populated from dropdownlists in my asp. However on pageload the labels aren't populating, they only populate once I change values in the dropdowns. So the variables are working with the labels, just not initially on page load.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim strDataCollection As String = ddlDataCollection.Text
Dim strYear As String = DdlYear.Text
Dim strSubject As String = DdlSubject.Text
Dim strTeachingGroup As String = DdlTeachingGroup.Text
Dim strSubgroup As String = ddlSubgroup.SelectedItem.Text
lblHeaderYear.Text = "Year " & strYear
lblHeaderDataCollection.Text = " " & strDataCollection
lblHeaderSubject.Text = " " & strSubject
lblHeaderTeachingGroup.Text = " " & strTeachingGroup
lblHeaderSubroup.Text = " " & strSubgroup
If strTeachingGroup = "Select All" Then
lblHeaderTeachingGroup.Visible = False
Else
lblHeaderTeachingGroup.Visible = True
End If
If strSubgroup = "Select All" Then
lblHeaderSubroup.Visible = False
Else
lblHeaderSubroup.Visible = True
End If
End Sub
The asp for my labels is:
<div class="centeronpage">
<asp:Label ID="lblHeaderYear" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderDataCollection" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderSubject" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderTeachingGroup" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderSubroup" runat="server" Text="" CssClass="header"></asp:Label>
</div>
EDIT ANSWER
I created the following PreRender as suggested below. I then included OnPreRender="Page_PreRender" in one of the label elements and this seemed to trigger the prerender.
Protected Sub Page_PreRender(sender As Object, e As EventArgs)
Dim strDataCollection As String = ddlDataCollection.Text
Dim strYear As String = DdlYear.Text
Dim strSubject As String = DdlSubject.Text
Dim strTeachingGroup As String = DdlTeachingGroup.Text
Dim strSubgroup As String = ddlSubgroup.SelectedItem.Text
lblHeaderYear.Text = "Year " & strYear
lblHeaderDataCollection.Text = " " & strDataCollection
lblHeaderSubject.Text = " " & strSubject
lblHeaderTeachingGroup.Text = " " & strTeachingGroup
lblHeaderSubroup.Text = " " & strSubgroup
End Sub
EDIT - DDL Binding
<asp:Label ID="lblHeaderYear" runat="server" Text="" CssClass="header" OnPreRender="Page_PreRender"></asp:Label>
<asp:Label ID="lblHeaderDataCollection" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderSubject" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderTeachingGroup" runat="server" Text="" CssClass="header"></asp:Label>
<asp:Label ID="lblHeaderSubroup" runat="server" Text="" CssClass="header"></asp:Label>
I've not checked it, but I think the problem is as the Page_load time, there's actually no selectditem. I would suggest trying to bind the labels in the prerender event, where dropdowns should actually have selected items (the first one if you didn't specify anything else)
EDIT :
you should do that for your prerender event :
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.Load
Dim strDataCollection As String = ddlDataCollection.Text
Dim strYear As String = DdlYear.Text
Dim strSubject As String = DdlSubject.Text
Dim strTeachingGroup As String = DdlTeachingGroup.Text
Dim strSubgroup As String = ddlSubgroup.SelectedItem.Text
lblHeaderYear.Text = "Year " & strYear
lblHeaderDataCollection.Text = " " & strDataCollection
lblHeaderSubject.Text = " " & strSubject
lblHeaderTeachingGroup.Text = " " & strTeachingGroup
lblHeaderSubroup.Text = " " & strSubgroup
End Sub
Note the "Handles Me.Load" after your PreRender event declaration. This is how you actually override the page's PreRender event , exactly as you do it for your PageLoad. You should then remove all prerender event on your labels in you aspx page.
Please note that you can also make use of the AutoEventWireup Page attribute :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
This will allow you, for Page events only, to tell .NET to automatically override page events if a method with the same name is defined in your codebehind. In other words, you'd be able to remove the "Handles Me.xxx" after event declaration.
This is my part of code for the grid view
<asp:GridView ID="gridViewCourse"
runat="server"
AutoGenerateColumns="False"
onrowcancelingedit="gridViewCourse_RowCancelingEdit"
onrowdeleting="gridViewCourse_RowDeleting" onrowediting="gridViewCourse_RowEditing"
onrowupdating="gridViewCourse_RowUpdating"
onrowcommand="gridViewCourse_RowCommand"
datakeynames="CourseId"
ShowFooter="True">
.....
<asp:TemplateField HeaderText="Fichier">
<EditItemTemplate>
<asp:FileUpload ID="FileUploadFichier" CssClass="upload" runat="server" Text='<%#Eval("Fichier") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFichier" runat="server" Text='<%#Eval("Fichier") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="FileUploadFichier" CssClass="upload" runat="server" />
<asp:RequiredFieldValidator ID="rfvFichier" runat="server" ControlToValidate="FileUploadFichier" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
....
This my method "onrowcommand="gridViewCourse_RowCommand""
Protected Sub gridViewCourse_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName.Equals("AddNew") Then
Dim txtId As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrId"), TextBox)
Dim txtCours As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrCours"), TextBox)
Dim txtPrix As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrPrix"), TextBox)
Dim txtTutor As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrTuteur"), TextBox)
con.Open()
Dim cmd As New SqlCommand(((("insert into Courses(CourseID,CourseName,Price,Tutor) values('" + txtId.Text & "','") + txtCours.Text & "','") + txtPrix.Text & "','") + txtTutor.Text & "')", con)
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result = 1 Then
BindCoursesDetails()
lblresult.ForeColor = Color.Green
lblresult.Text = " Details inserted successfully"
Else
lblresult.ForeColor = Color.Red
lblresult.Text = " Details not inserted"
End If
End If
Dim upload As FileUpload = DirectCast(gridViewCourse.FindControl("FileUploadFichier"), FileUpload)
upload.SaveAs((Server.MapPath(Request.ApplicationPath & "/CoursesFiles/" & Path.GetFileName(FileUpload1.PostedFile.FileName))))
End Sub
The problem is The cast to upload (As FileUpload) contain nothing after...
The others are good and effective...
How I can acces to the FileUpload1 and save it ?
Thanks Frank
You're using two fileupload controls with the same id, try different IDs
and replace this line
Dim upload As FileUpload = DirectCast(gridViewCourse.FindControl("FileUploadFichier"), FileUpload)
with this one
Dim upload As FileUpload = DirectCast(gridViewCourse.FooterRow.FindControl("FileUploadFichier"), FileUpload)
Protected Sub gridViewCourse_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName.Equals("AddNew") Then
Dim txtId As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrId"), TextBox)
Dim txtCours As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrCours"), TextBox)
Dim txtPrix As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrPrix"), TextBox)
Dim txtTutor As TextBox = DirectCast(gridViewCourse.FooterRow.FindControl("txtftrTuteur"), TextBox)
Dim upload As FileUpload = DirectCast(gridViewCourse.FindControl("FileUploadFichier"), FileUpload)
upload.SaveAs((Server.MapPath(Request.ApplicationPath & "/CoursesFiles/" & Path.GetFileName(FileUpload1.PostedFile.FileName))))
con.Open()
Dim cmd As New SqlCommand(((("insert into Courses(CourseID,CourseName,Price,Tutor) values('" + txtId.Text & "','") + txtCours.Text & "','") + txtPrix.Text & "','") + txtTutor.Text & "')", con)
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result = 1 Then
BindCoursesDetails()
lblresult.ForeColor = Color.Green
lblresult.Text = " Details inserted successfully"
Else
lblresult.ForeColor = Color.Red
lblresult.Text = " Details not inserted"
End If
End If
End Sub
I have to put the cast before BindCoursesDetails()