Access to a file upload in gridView footer - asp.net

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()

Related

ASP.NET delete specific rows from gridview

I need help with following problem.
I try to delete specific rows from gridview.
Code bellow works well, but when page is loading its show all data in database.
How can I filter data? I mean when page is loading it shows nothing, but after type some text in text box, it shows me rows with that text and I can delete some of that rows with text from text box by check checkbox and button.
This is my code. Pls help me.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If IsPostBack Then
GetData()
End If
BindGrid()
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString()
Dim query As String = "select * from TestCustomers"
Dim con As New SqlConnection(constr)
Dim sda As New SqlDataAdapter(query, con)
Dim dt As New DataTable()
sda.Fill(dt)
gvAll.DataSource = dt
gvAll.DataBind()
End Sub
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvAll.PageIndex = e.NewPageIndex
gvAll.DataBind()
SetData()
End Sub
Private Sub GetData()
Dim arr As ArrayList
If ViewState("SelectedRecords") IsNot Nothing Then
arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
Else
arr = New ArrayList()
End If
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
For i As Integer = 0 To gvAll.Rows.Count - 1
If chkAll.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
If arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Remove(gvAll.DataKeys(i).Value)
End If
End If
End If
Next
ViewState("SelectedRecords") = arr
End Sub
Private Sub SetData()
Dim currentCount As Integer = 0
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
chkAll.Checked = True
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
For i As Integer = 0 To gvAll.Rows.Count - 1
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk IsNot Nothing Then
chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
If Not chk.Checked Then
chkAll.Checked = False
Else
currentCount += 1
End If
End If
Next
hfCount.Value = (arr.Count - currentCount).ToString()
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim count As Integer = 0
SetData()
gvAll.AllowPaging = False
gvAll.DataBind()
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
count = arr.Count
For i As Integer = 0 To gvAll.Rows.Count - 1
If arr.Contains(gvAll.DataKeys(i).Value) Then
DeleteRecord(gvAll.DataKeys(i).Value.ToString())
arr.Remove(gvAll.DataKeys(i).Value)
End If
Next
ViewState("SelectedRecords") = arr
hfCount.Value = "0"
gvAll.AllowPaging = True
BindGrid()
ShowMessage(count)
End Sub
Private Sub DeleteRecord(ByVal CustomerID As String)
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim query As String = "delete from TestCustomers where" & _
" CustomerID=#CustomerID"
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#CustomerID", CustomerID)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Private Sub ShowMessage(ByVal count As Integer)
Dim sb As New StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("alert('")
sb.Append(count.ToString())
sb.Append(" records deleted.');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), _
"script", sb.ToString())
End Sub
<asp:GridView ID="gvAll" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" DataKeyNames = "CustomerID"
PageSize = "10" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "ContactName" HeaderText = "Contact Name"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "Country" HeaderText = "Country"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "City" HeaderText = "City"/>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
<asp:HiddenField ID="hfCount" runat="server" Value = "0" />
<asp:Button ID="btnDelete" runat="server" Text="Delete Checked Records" OnClientClick = "return ConfirmDelete();" OnClick="btnDelete_Click" />
Even though your question is not clear , i will answer what i have understood.
you want to show all data on page load and on postback you want to show selected rows , right ?
if yes
try this code
If IsPostBack Then
GetData()
End If
else
BindGrid()
if this has not answered your question , please tell me what exactly you want to do.
This will delete all rows that had been selected.
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
If DataGridView1.SelectedRows.Count > 0 Then
DataGridView1.Rows.RemoveAt(DataGridView1.CurrentRow.Index)
Else
MessageBox.Show("You must select a row")
End If
End Sub
Use this it may help full to you
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
For Each gvrow As GridViewRow In gvDetails.Rows
'Finiding checkbox control in gridview for particular row
Dim chkdelete As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
'Condition to check checkbox selected or not
If chkdelete.Checked Then
'Getting UserId of particular row using datakey value
Dim usrid As Integer = Convert.ToInt32(gvDetails.DataKeys(gvrow.RowIndex).Value)
Using con As New SqlConnection("YOUR SQL DATABASE CONNECTION")
con.Open()
Dim cmd As New SqlCommand("delete from UserDetails where UserId=" & usrid, con)
cmd.ExecuteNonQuery()
con.Close()
End Using
End If
Next
BindUserDetails()
End Sub

Child gridview update event

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

Trouble with Listbox bind inside Gridview

I am a AS400 programmer asked to write a program in asp.net using vb.net. I have never done this before and I am having issues with populating a listbox in Gridview. I have researched this subject for days but all the code I have tried, found in examples, do not work. Please forgive any really bad code, with me being so new to .net, I am sure this could be written much better. I appreciate any help you may be able to offer. the grid is "AdjusterList" and the Listbox is called "MAICD". I think the 'failing/bad' code in
Public Sub AdjusterList_RowDataBound. It is giving me a null exception error the line before the databind; oCtrl.DataSource = oRs
I am using code given to me by a senior .net programmer, whom is not able to offer any more assistance to this newbie. Just Fyi....
Here is my aspx.
<div id="div1" runat="server">
<asp:GridView ID="AdjusterList" runat="server" Width="1100px"
ClientIDMode="Static" AllowSorting="True"
AutoGenerateColumns="False"
OnRowCommand="AdjusterList_RowCommand"
OnRowEditing="AdjusterList_RowEditing"
OnRowUpdating="AdjusterList_RowUpdating"
OnRowDeleting="AdjusterList_RowDeleting"
OnRowCancelingEdit="AdjusterList_RowCancelingEdit"
OnRowDataBound="AdjusterList_RowDataBound"
DataKeyNames="INSCD, INSSEQ"
ShowHeaderWhenEmpty="True" EditRowStyle-BackColor="#FF9900" PageSize="20"
EmptyDataText="NO RECORDS FOUND FOR THIS INSURER"
ShowFooter="True"EnableViewState="true">
<EditRowStyle BackColor="#FF9900" />
<RowStyle BackColor="White" ForeColor="Black" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton id="btnedit" runat="server" CommandName="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton id="btnupdate" runat="server" CommandName="Update" Text="Save" />
<asp:LinkButton id="btncancel" runat="server" CommandName="Cancel" Text=Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton id="btninsert" runat="server" CommandName="Insert" Text="Insert"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Mail Code" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblmaicd" runat="server" Text='<%# Bind("MAICD")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text"
DataValueField='<%# Bind("MAICD")%></asp:ListBox>
</EditItemTemplate>
<FooterTemplate>
<asp:ListBox ID="MAICD" runat="server" width="200" DataTextField="Text">
</asp:ListBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My code behind...
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class EditAdjusterData
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e AsSystem.EventArgs)
Dim sAdjuster As String = Session("Adjuster")
Dim sSeqNo As String = Session("SeqNo")
PopulateEdit(sAdjuster, sSeqNo, dateok)
If IsPostBack Then
'divEdit.Visible = False
'divSelect.Visible = True
'ShowForm()
Else
AdjusterList.DataBind()
'divEdit.Visible = True
'divSelect.Visible = False
End If
End Sub
Protected Sub PopulateEdit(sValue As String, sValue2 As String, sValue3 As String)
' CALL TO PGRTSTLIB FILE INSP TO GET INSURER NAME
' 2ND CALL TO PGRTSTLIB FILE INSD
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1;
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
sSql = "SELECT INSCD, INSSEQ, MAICD, MAISEQ, (substr(char(EFFDT),5,2) || '-' || substr(char(EFFDT),7,2) || '-' || substr(char(EFFDT),1,4)) AS EFFDT, (substr(char(CANDT),5,2) || '-' || substr(char(CANDT),7,2) || '-' || substr(char(CANDT),1,4)) AS CANDT, ACCFIL FROM PGRTSTLIB.INSD WHERE INSCD = '" & sValue & "' "
oCmd = New OleDbCommand(sSql, oConn)
Session(INSCD) = INSCD
Session(EFFDT) = EFFDT
Session(MAICD) = MAICD
Session("CANDT") = CANDT
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "Data")
Dim sMailCode As String = " "
Dim sMailSeq As String = " "
Dim pRow As DataRow
For Each pRow In oRs.Tables("Data").Rows
sMailCode = pRow("MAICD").ToString()
Next
Session(sMailCode) = MAICD
Session(MAICD) = sMailCode
Session(sMailCode) = sMailCode
AdjusterList.DataSource = oRs
'AdjusterList.DataBind()
'If sMailCode <> " " Then
' PopulateMailCode(sMailCode)
'End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Protected Sub AdjusterList_PageIndexChanging(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
AdjusterList.PageIndex = e.NewPageIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowCommand(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
End Sub
Protected Sub AdjusterList_RowCreated(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
End Sub
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object,
ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
'If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
BindAjusterList()
End If
End If
End Sub
Public Sub BindAjusterList()
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1; "
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
'sSql = "SELECT MAICD as Value, MAICD AS Text from PGRTSTLIB.INSM order by MAICD"
sSql = "SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"
oCmd = New OleDbCommand(sSql, oConn)
'oCmd.Parameters.Add(New SqlParameter("#Type", Insurer))
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "ListBox")
Dim oCtrl As ListBox
oCtrl = AdjusterList.FindControl("MAICD")
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
oCtrl.Items.Insert(0, New ListItem(String.Empty, String.Empty))
If Len(sValue) > 0 Then
oCtrl.SelectedValue = sValue
Else
sValue = " "
End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Public Sub AdjusterList_RowEditing(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
AdjusterList.EditIndex = e.NewEditIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowUpdating(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
' Dim row As GridViewRow = DirectCast(SubsidaryList.Rows(e.RowIndex), GridViewRow)
Dim INSCD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells (0).FindControl ("INSCD"), TextBox).Text
Dim INSSEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(1).FindControl("INSSEQ"), TextBox).Text
Dim MAICD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(2).FindControl("MAICD"), ListBox).Text
Dim MAISEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(3).FindControl("MAISEQ"), TextBox).Text
Dim EFFDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(4).FindControl("EFFDT"), TextBox).Text
Dim CANDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(5).FindControl("CANDT"), TextBox).Text
Dim ACCFIL As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(6).FindControl("ACCFIL"), TextBox).Text
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
' New Data to DataBind to sql datasource and resend page after RECORD updated
Response.Redirect("EditAdjusterData.aspx")
End Sub
Protected Sub AdjusterList_RowCancelingEdit() Handles AdjusterList.RowCancelingEdit
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
End Sub
End Class
I am so new to .net and I may not fully understand every example. I think the senior .net programmers think it is funny : (
Thanks so much and please feel free to contact me with any help you may be able to offer. I just need the darn listbox to populate. I removed any code I considered unrelated to this listbox issue.
In your markup, you should change the DataValueField property of your ListBox to the "Value" string, because it's the alias you are giving to the property in the query ("SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"):
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text" DataValueField="Value"></asp:ListBox>
Also, in RowDataBound event, you are retrieving the ListBox instance for that row using the FindControl method, but then you are retrieving it again in the BindAjusterList() method. Try changing the method to receive the control found:
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object, ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
BindAjusterList(MAICD)
End If
End If
End Sub
Public Sub BindAjusterList(ByVal oCtrl As ListBox)
' existing logic
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
' existing logic
End Sub

DropDownList after postback all values/index lost

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.

DropDownList is not posting back

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).

Resources