I have a survey page, where i insert radio buttons dinamically in form load event. When i click the button to send the results, after postback, the radio buttons are still there, with the checked state correctly. But if i do some code, in the code behind, that tries to check if one of them is checked (by FindControl(id)), the page crashes. I canĀ“t do debug, so i don't know what error is.
<%# Control language="vb" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<%# Register TagPrefix="dnn" TagName="USER" Src="~/Admin/Skins/User.ascx" %>
<style>
body {background-image:none; background-color:transparent;}
</style>
<div style="float:left; width:420px; height:335px;" id="divPerguntas" enableviewstate="true" runat="server"></div>
<div style="float:left; width:420px; height:75px;"><asp:ImageButton ImageUrl="/Portals/_default/Skins/AdWin/img/Enviar.png" id="imgEnviar" runat="server" style="cursor:pointer;" /></div>
<div id="ContentPane" runat="server"></div>
<script runat="server">
Protected Sub EnviarClick() Handles imgEnviar.Click
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim checkedGroup As Boolean = False
Dim insertList As New DataTable
Dim ColumnIDSurveyOption As New DataColumn("c", GetType(Integer))
insertList.Columns.Add(ColumnIDSurveyOption)
Dim row As DataRow
For Each dr As DataRow In dt.Rows
If FirstQuestion Then
SurveyID = dr("SurveyID")
FirstQuestion = False
End If
If SurveyID <> dr("SurveyID") Then
SurveyID = dr("SurveyID")
checkedGroup = False
End If
If SurveyID = dr("SurveyID") And checkedGroup = False Then
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
If radiobuttonToCheck.Checked Then
checkedGroup = True
row = insertList.NewRow()
row("insertList") = dr("SurveyOptionID")
insertList.Rows.Add(row)
End If
End If
Next
If checkedGroup = True Then
Dim dnnUserCtrl As New DotNetNuke.Entities.Users.UserController
For Each dr As DataRow In insertList.Rows
sql = "INSERT INTO AdWin_Demo.dbo.Adwin_RespostasDadas (IDUser, SurveyOptionID) SELECT " & dnnUserCtrl.GetCurrentUserInfo.UserID & ", " & dr("SurveyOptionID").ToString()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
Next
Else
Response.Write("Nao respondeste a tudo")
End If
End If
myReader.Close()
conexao.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.EnableViewState = True
'If Not Page.IsPostBack Then
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, S.Question, SO.OptionName, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, S.SurveyID, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim ActualDiv As System.Web.UI.HtmlControls.HtmlGenericControl
For Each dr As DataRow In dt.Rows
If SurveyID = dr("SurveyID") Then
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Else
SurveyID = dr("SurveyID")
If FirstQuestion = False Then
Dim hr2 As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr2)
End If
Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("DIV")
div.Style.Add("float", "left")
div.Style.Add("width", "400px")
div.Style.Add("color", "#777")
div.Style.Add("font-size", "11px")
div.Style.Add("line-height", "15px")
divPerguntas.Controls.Add(div)
ActualDiv = div
ActualDiv.InnerText = dr("Question").ToString()
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
FirstQuestion = False
End If
Next
Dim hr As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr)
End If
myReader.Close()
conexao.Close()
End Sub
</script>
Try to add controls to the page in PreInit event and see if you can access data correctly. More details here http://msdn.microsoft.com/en-us/library/ms178472.aspx
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
->
Dim radiobuttonToCheck As RadioButton = Me.FindControl(dr("SurveyOptionID").ToString())
Related
I have a masterpage that has this code in it:
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Session("userid") = Nothing Then
txtLoginUser.Visible = True
txtLoginPass.Visible = True
Else
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim useridComm As String = "SELECT name, surname FROM users WHERE user_id=#userid"
Dim sqlUserID As New SqlCommand
conn.Open()
Dim userid As String = Session("UserID")
sqlUserID = New SqlCommand(useridComm, conn)
sqlUserID.Parameters.AddWithValue("#userid", Convert.ToInt32(userid))
Dim datareader As SqlDataReader = sqlUserID.ExecuteReader()
datareader.Read()
If datareader.HasRows Then
userid = Session("UserID")
lblLoggedIn.Text = "[Welcome, " + datareader("name").ToString() & " " & datareader("surname").ToString() + " ]"
txtLoginUser.Visible = False
txtLoginPass.Visible = False
lblUsername.Visible = False
lblRegister.Visible = False
btnLogin.Visible = False
lblUsername0.Visible = False
End If
datareader.Close()
conn.Close()
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim loginSQL As New SqlCommand
Dim loginComm As String
Dim CommonFunctions As New CommonFunctions()
Dim dec_pass As String = CommonFunctions.EncryptPassword(txtLoginPass.Text.Trim)
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
loginComm = "SELECT user_id FROM users WHERE username=#username and password=#password"
conn.Open()
loginSQL = New SqlCommand(loginComm, conn)
loginSQL.Parameters.AddWithValue("#username", txtLoginUser.Text.ToString)
loginSQL.Parameters.AddWithValue("#password", dec_pass)
Dim dr As SqlDataReader = loginSQL.ExecuteReader()
dr.Read()
If dr.HasRows Then
Session("UserID") = dr("user_id")
ElseIf dr.HasRows = False Then
lblRegister.ForeColor = Drawing.Color.Red
lblRegister.Text = "Incorrect Username/Password."
End If
dr.Close()
conn.Close()
Response.Redirect("Default.aspx")
End Sub
</script>
On Button1 click the script should get the user_id by using the datareader and create a Session("UserID") and pass it to Default.aspx. Default.aspx then gets the Session("UserID") and searches for a user_id that has the same value and checks the roles using user_roles table, and if the role_id is 4 then tblAdmin is shown, otherwise, it isn't.
This is the code for Default.aspx:
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim UserID As Integer = Convert.ToInt32(Session("UserID"))
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim userTypeCommand As String = "SELECT role_id FROM users_role WHERE user_id=#UserID"
Dim userTypeSQL As New SqlCommand
conn.Open()
Try
userTypeSQL = New SqlCommand(userTypeCommand, conn)
userTypeSQL.Parameters.AddWithValue("#UserID", UserID)
Dim datareader As SqlDataReader = userTypeSQL.ExecuteReader
If datareader("role_id").ToString = "4" Then
tblAdmin.Enabled = True
tblAdmin.Visible = True
ElseIf datareader("role_id").ToString IsNot "4" Then
tblAdmin.Visible = False
End If
Catch ex As Exception
End Try
conn.Close()
End Sub
Protected Sub btnCreateArticle_Click(sender As Object, e As EventArgs) Handles btnCreateArticle.Click
Response.Redirect("addArticle.aspx")
End Sub
Protected Sub btnAdmin_Click(sender As Object, e As EventArgs) Handles btnAdmin.Click
Response.Redirect("Admin.aspx")
End Sub
End Class
When I debug, after I press the 'Login' button the user_id (Session('UserID') remains 0, when the user_id of the user I used to log with is '12' in the table.
What Am I doing wrong?
I am using ASP.NET/VB.NET and SQL Server 2012.
Fixed it. Had a missing datareader.Read().
Whenever I try this code the page remains refreshing.
Imports System.Data.SqlClient
Imports System.Data
Partial Class ProjectReport
Inherits System.Web.UI.Page
Private myTotal As Decimal = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load, Chart1.Load
Dim ProjectID As Integer = Session("project_id")
Session("ProjectID") = ProjectID
lblProjNameHeading.Text = "[ " + ProjectID.ToString + " ]"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim projComm As String = "SELECT project_id, project_start, project_finish, project_budget, project_cost FROM projects WHERE project_id=#parameter"
Dim projSQL As New SqlCommand
conn.Open()
projSQL = New SqlCommand(projComm, conn)
projSQL.Parameters.AddWithValue("#parameter", ProjectID.ToString)
Dim datareader As SqlDataReader = projSQL.ExecuteReader()
While datareader.Read
lblProjectCode.Text = datareader("project_id").ToString
lblProjectStart.Text = datareader("project_start").ToString
lblProjectStart2.Text = datareader("project_start").ToString
lblProjectEnd.Text = datareader("project_finish").ToString
lblProjectEnd2.Text = datareader("project_finish").ToString
lblProjectBudget.Text = datareader("project_budget").ToString
lblProjectBudget2.Text = datareader("project_budget").ToString
lblProjectCost.Text = datareader("project_cost").ToString
lblProjectCost2.Text = datareader("project_cost").ToString
' lblProjectLeader.Text = datareader("project_cost").ToString
'lblProjectExpenditures.Text = agdgssag
Dim StartDate As DateTime = datareader("project_start")
Dim FinishDate As DateTime = datareader("project_finish")
Dim today As DateTime = DateTime.Now
Dim sumDays = (FinishDate - StartDate).TotalDays
Dim daysToNow = (today - StartDate).TotalDays
Dim percentage = daysToNow / sumDays * 100
Dim percentageLeft = 100 - percentage
Session("PercentageCompleted") = percentage
Session("PercentageLeft") = percentageLeft
GetTable()
Expenditures()
lblProjectPercentage.Text = percentage.ToString("N2") + "%"
End While
datareader.Close()
conn.Close()
If Not Page.IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim query As New SqlCommand("SELECT Items.item_name, Items.item_cost, project_items.item_quantity FROM Items INNER JOIN project_items ON items.item_id = project_items.item_id WHERE project_items.project_id = #parameter", conn)
conn.Open()
query.Parameters.AddWithValue("#parameter", Convert.ToInt32(Session("ProjectID")))
Dim da As New SqlDataAdapter(query)
da.SelectCommand = query
Dim table As New DataTable()
da.Fill(table)
grdItems.DataSource = table
conn.Close()
grdItems.DataBind()
End Sub
Protected Sub grdItems_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowView As DataRowView = CType(e.Row.DataItem, DataRowView)
myTotal += (CDec(rowView("item_cost")) * CDec(rowView("item_quantity")))
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lblTotalPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label)
lblTotalPrice.Text = myTotal.ToString()
End If
End Sub
Function GetTable() As DataTable
Dim table As New DataTable
table.Columns.Add("Percentage Completed", GetType(Double))
table.Columns.Add("Percentage Not-Completed", GetType(Double))
table.Rows.Add(Session("PercentageCompleted"))
table.Rows.Add(Session("PercentageLeft"))
Chart1.DataSource = table
Chart1.Series("Series1").XValueMember = "Percentage Not-Completed"
Chart1.Series("Series1").YValueMembers = "Percentage Completed"
Chart1.DataBind()
Return table
End Function
Private Sub Expenditures()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim projExpComm As String = "SELECT Items.item_cost, project_items.item_quantity FROM Items INNER JOIN project_items ON items.item_id = project_items.item_id WHERE project_items.project_id = #parameter"
Dim projExpSQL As New SqlCommand
conn.Open()
projExpSQL = New SqlCommand(projExpComm, conn)
projExpSQL.Parameters.AddWithValue("#parameter", Session("project_id"))
Dim datareader As SqlDataReader = projExpSQL.ExecuteReader()
datareader.Read()
While datareader.Read
While datareader.HasRows
Dim ItemsTotal As Double = 0
For Each row In datareader
Dim ItemCost = datareader("item_cost")
Dim ItemQuantity = datareader("item_quantity")
Dim ItemsSubTotal As Double = ItemCost * ItemQuantity
ItemsTotal = ItemsSubTotal
Next
ItemsTotal = ItemsTotal + ItemsTotal
lblProjectExpenditures.Text = ItemsTotal.ToString
End While
End While
datareader.Close()
conn.Close()
End Sub
End Class
Why is it happening?
I checked for un-closed connections / datareaders but everything was ok.
Is there something I'm missing ?
You page load method is executed completely each time you do a post back. You should be checking to see !isPostBack to prevent the complete execution of that code.
Do i need to have a new ID generate within vb if I have it set to AutoID in the table itself?
I currently have
Protected Sub deleteButton_Click(sender As Object, e As System.EventArgs) Handles deleteButton.Click
Dim deleteSQL As String
deleteSQL = "DELETE FROM Authors WHERE au_id=#au_id"
Dim myConnection As New SqlConnection(connectionString)
Dim myCommand As New SqlCommand(deleteSQL, myConnection)
myCommand.Parameters.AddWithValue("#au_id", authorDropDownList.SelectedItem.Value)
Dim successBoolean As Boolean = True
Dim index As Integer = authorDropDownList.SelectedIndex
Try
myConnection.Open()
successBoolean = myCommand.ExecuteNonQuery
'authorLabel.Text = "Record Deleted"
'authorLabel.Visible = True
Catch ex As Exception
successBoolean = False
authorLabel.Text = "Error deleting author. " & ex.Message
authorLabel.Visible = True
Finally
myConnection.Close()
End Try
If successBoolean Then
FillAutherList(index)
authorDropDownList_SelectedIndexChanged(sender, e)
authorLabel.Text = "Record Deleted"
authorLabel.Visible = True
End If
End Sub
Dim insertSQL As New StringBuilder
Dim currentDate As String
currentDate = DateTime.Now.ToString
insertSQL.Append("INSERT INTO Story_Table (Author,Content,Submission_Date)") 'Inserts new story
insertSQL.Append(" VALUES (#Author,#Content,#Submission_Date)") 'Sets the story values
Dim myConnection As New SqlConnection(connectionString)
Dim myCommand As New SqlCommand(insertSQL.ToString, myConnection)
With myCommand.Parameters 'Do this next
.AddWithValue("#Author", authorTextBox.Text)
.AddWithValue("#Content", storyTextBox.Text)
.AddWithValue("#Submission_Date", currentDate)
End With
Dim successBoolean As Boolean = True
Try
myConnection.Open()
successBoolean = myCommand.ExecuteNonQuery
resultLabel.Text = "Thanks for the Story! Look for it on the homepage."
resultLabel.Visible = True
Catch ex As Exception
successBoolean = False
resultLabel.Text = "Error inserting story. " & ex.Message
resultLabel.Visible = True
storyLabel.Text = storyTextBox.Text
storyLabel.Visible = True
Finally
myConnection.Close()
End Try`
i have to insert some data value and value like this picture on insert.aspx
And how i show like this to update the data update.aspx
So how to make check box on update.aspx check automatic like on insert.aspx
on Insert.aspx.vb
Protected Sub insertdata()
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_inserttrainer"
cmd.Parameters.AddWithValue("#id", txtKode.Text)
cmd.Parameters.AddWithValue("#nama", txtnama.Text)
cmd.Parameters.AddWithValue("#status", txtstatus.SelectedValue)
cmd.Parameters.AddWithValue("#alamat", txtalamat.Text)
cmd.Parameters.AddWithValue("#telp", txttel.Text)
cmd.Parameters.AddWithValue("#hp", txthp.Text)
cmd.Parameters.AddWithValue("#email", txtemail.Text)
cmd.ExecuteNonQuery()
cls.closeconnection()
End Sub
Protected Sub savedatamateri()
Dim cbterpilih As Boolean = False
Dim cb As CheckBox = Nothing
Dim n As Integer = 0
Do Until n = gridsecond.Rows.Count
cb = gridsecond.Rows.Item(n).FindControl("chkStatus")
If cb IsNot Nothing AndAlso cb.Checked Then
cbterpilih = True
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandText = "Insert Into m_trainer_detil (trainer_id, materi_id)"
cmd.CommandText &= "values(#triner, #materi)"
Dim com As HiddenField = CType(gridsecond.Rows(n).FindControl("HiddenField2"), HiddenField)
cmd.Parameters.AddWithValue("#triner", txtKode.Text)
cmd.Parameters.AddWithValue("#materi", com.Value)
cmd.ExecuteNonQuery()
cls.closeconnection()
End If
n += 1
Loop
End Sub
Protected Sub insert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles insert.Click
If txtalamat.Text = "" Then
labelran.Text = "Tolong isi Alamat"
ElseIf txtemail.Text = "" Then
labelran.Text = "Tolong isi Email"
ElseIf txtnama.Text = "" Then
labelran.Text = "Tolong isi Nama"
ElseIf txttel.Text = "" Then
labelran.Text = "Tolong isi Telepon"
ElseIf txthp.Text = "" Then
labelran.Text = "Tolong isi Handphone"
Else
insertdata()
savedatamateri()
listhendle()
End If
End Sub
and for update.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
listhendle()
listmateri()
End If
End Sub
Protected Sub listhendle()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_trainer] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
griddata.DataSource = ds
griddata.DataBind()
End Sub
Protected Sub listmateri()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_materi] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
gridsecond.DataSource = ds
gridsecond.DataBind()
End Sub
Protected Sub griddata_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles griddata.SelectedIndexChanging
Dim kode As HiddenField = CType(griddata.Rows(e.NewSelectedIndex).FindControl("HiddenField1"), HiddenField)
txtKode.Text = kode.Value
txtnama.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(1).Text, " ", "")
txtalamat.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(2).Text, " ", "")
txttel.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(3).Text, " ", "")
txthp.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(4).Text, " ", "")
txtstatus.SelectedValue = Replace(griddata.Rows(e.NewSelectedIndex).Cells(5).Text, " ", "")
txtemail.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(6).Text, " ", "")
End Sub
But i don't know how connect materi with database
Thank You
It looks like you are storing the materi_id in the table m_trainer. So it looks like you would need to set up an OnRowDataBound event on your "gridSecond" GridView. Within the OnRowDatabound event get a dataset for the selected trainer_id and if the materi_id exists within that dataset set its checked value as true.
I have a gridview with 4 columns, three of them are template fields where the user can enter the information needed and click a button to submit it to the database. I have 2 issues:
When I click my button to add a second row... the data in the first row posts
disappears. I want to be able to add the row without the first row of information
disappearing for multiple record entry situations. My code follows:
Private Sub SetInitialRow()
Dim dts As New DataTable()
Dim drs As DataRow = Nothing
dts.Columns.Add(New DataColumn("Approval Date", GetType(String)))
dts.Columns.Add(New DataColumn("Total Amount", GetType(String)))
dts.Columns.Add(New DataColumn("Comments", GetType(String)))
dts.Columns.Add(New DataColumn("Initials", GetType(String)))
drs = dts.NewRow()
drs("Approval Date") = String.Empty
drs("Total Amount") = String.Empty
drs("Comments") = String.Empty
drs("Initials") = String.Empty
dts.Rows.Add(drs)
ViewState("CurrentTable") = dts
gvOLIAdj.DataSource = dts
gvOLIAdj.DataBind()
End Sub
Private Sub AddNewRowToGrid()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
drCurrentRow = dtCurrentTable.NewRow()
drCurrentRow("Approval Date") = box1.Text
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
'dtCurrentTable.Rows(i - 1)("Initials") =
rowIndex += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
gvOLIAdj.DataSource = dtCurrentTable
gvOLIAdj.DataBind()
End If
Else
Response.Write("ViewState is null")
End If
'Set Previous Data on Postbacks
SetPreviousData()
End Sub
Private Sub SetPreviousData()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dats As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
If dats.Rows.Count > 0 Then
For i As Integer = 0 To dats.Rows.Count - 1
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
box1.Text = dats.Rows(i)("Approval Date").ToString()
box2.Text = dats.Rows(i)("Total Amount").ToString()
box3.Text = dats.Rows(i)("Comments").ToString()
rowIndex += 1
Next
End If
End If
End Sub
Protected Sub btnAddNewRow_Click(sender As Object, e As EventArgs) Handles btnAddNewRow.Click
AddNewRowToGrid()
End Sub
When I try to write a loop that will loop through each of the template fields to grab
the data and put it into my database it doesn't recognize that I have data in the
template fields? This is what I have tried thus far to no avail...
Protected Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
For Each row As GridViewRow In gvOLIAdj.Rows
For Each gv As GridViewRow In gvOLIAdj.Rows
Dim appDt As String = (Rows(rowIndex).Cells(1).FindControl("txtAdjAppr")), TextBox)
Dim approvalDt As String = CType(gv.FindControl("txtAdjAppr"), TextBox).Text
Dim totalAmt As String = CType(gv.FindControl("txtAdjAmt"), TextBox).Text
Dim comments As String = CType(gv.FindControl("txtcmmts"), TextBox).Text
Dim intitials As String = DirectCast(gv.FindControl("total"), TextBox).Text
Next
End Sub
In your AddNewRowToGrid method you are doing the following:
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
What's wrong here is the updating of the row in dtCurrentTable.Rows(i - 1). You are updating the values in the row above that which you wish to update.