ASP.NET Session remains '0' - asp.net

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

Related

Add new data to textbox when selecting item from combobox

How can I automatically input a number to a textbox after clicking a button upon selecting an item from a combobox. All I know to do is to get the data from the combobox to textbox. But what I would like to do is to add data to a textbox once the item is selected.
This is My Code:
Imports System.Data.OleDb
Imports System.Data
Public Class voting1
Dim con As New OleDbConnection
Dim Com As New OleDbCommand
Dim ComInsert As New OleDbCommand
Dim ComUpdate As New OleDbCommand
Dim ComDelete As New OleDbCommand
Dim aAdapter As New OleDbDataAdapter
Dim Dset As New DataSet
Private Sub voting1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ConProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
Try
Try
con.ConnectionString = ConProvider
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As Exception
MsgBox("No Connection Established")
End Try
Me.fill()
user.Visible = False
user.Text = Form1.usertxt.Text
Catch ex As Exception
End Try
End Sub
Private Sub fill()
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from candidate"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
While (dataRead.Read())
presbox.Items.Add(dataRead("President"))
vpbox.Items.Add(dataRead("VicePresident"))
secbox.Items.Add(dataRead("Secretary"))
treasbox.Items.Add(dataRead("Treasurer"))
End While
aAdapter.Dispose()
End Sub
Public Sub Initialize()
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As System.Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "ERROR CONNECTION")
End Try
End Sub
Private Sub bo()
Dim con1 As New OleDbConnection
Dim cmd As New OleDbCommand
con1.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
cmd.Connection = con1
con1.Open()
Dim num As Integer
cmd.CommandText = "SELECT pres1 FROM vote1"
If IsDBNull(cmd.ExecuteScalar) Then
num = 1
samp.Text = num
Else
num = 1
samp.Text = num
End If
cmd.Dispose()
con1.Close()
con1.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Call Initialize()
If presbox.Text = "" Or vpbox.Text = "" Or secbox.Text = "" Or treasbox.Text = "" Then
MsgBox("All Fields are required, Check the fields", MsgBoxStyle.Information, "Required Fiels")
Exit Sub
End If
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from [vote] where username = '" & user.Text & "'"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
If Not dataRead.HasRows Then
ComInsert.CommandText = "INSERT INTO vote([username],[president],[vicePresident],[secretary],[treasurer])" & _
"VALUES('" & user.Text & "','" & presbox.Text & "','" & vpbox.Text & "','" & secbox.Text & "','" & treasbox.Text & "')"
ComInsert.Connection = con
ComInsert.ExecuteNonQuery()
MsgBox("Voting Successful!", MsgBoxStyle.Information, "NEW RECORD")
Form1.Show()
Me.Close()
aAdapter.Dispose()
ComInsert.Dispose()
Else
MsgBox("WARNING: User Voted Already!!", MsgBoxStyle.Exclamation, "ERROR SAVING DATA")
Me.Close()
Form1.Show()
End If
Catch ex As Exception
End Try
End Sub
End Class
There are a couple of ways to do this if I am understanding what you are wanting.
1.) We can just check if there is anything in the combobox.text property.
If String.IsNullOrEmpty(cbobox.text) Then
Perform the logic of adding data to textbox here.
cbobox.text = null
End If
That is the most simple way, but you will have to set the combobox back to null after the data is added to make it work again.
2.) We can make use of the Combobox.SelectedIndexChanged method.
Here is the documentation website: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged.aspx
Here is an example:
private void ComboBox1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
perform logic here
}
Hope this helps.
Private Sub p1()
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Com = con.CreateCommand
Com.CommandText = "SELECT COUNT(vote.presnum) as countofpres FROM vote WHERE presnum ='1';"
Dim dt As OleDb.OleDbDataReader = Com.ExecuteReader
dt.Read()
Dim countpres As Integer = dt("countofpres")
Me.pres1.Text = countpres
dt.Close()
End Sub
here it is Jlott

ASP.NET Page keeps refreshing (VB.NET)

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.

Code behind isn't finding radio buttons after postback

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

Adding a new record to an Access database via vb.net

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`

How to check a check box automatically on vb.net asp.net?

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.

Resources