database cannot update textbox value in vb.net - asp.net

I am doing a update profile in a web application using vb.net. At first I read the database and put the data into the textbox, then i change the data inside the textbox and click the 'update' button. The problem is when i click the button, it won't update the latest value that i typed into the textbox. It will still update the value where i read from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End Sub
'above this image is how i read from the database.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim errFirstName As Boolean = True
Dim errLastName As Boolean = True
Dim errCPassword As Boolean = True
Dim errNPassword As Boolean = True
Dim errDob As Boolean = True
Dim errEmail As Boolean = True
Dim errNumber As Boolean = True
Dim errAddress As Boolean = True
Dim newFName, newLName, newPassword, newAddress, newNumber, newEmail, newDob As String
If txtFirstName.Text = "" Then
txtFirstName.BackColor = Drawing.Color.LightPink
lblFirstName.Text = "cannot be empty"
ElseIf Not Regex.Match(txtFirstName.Text, "^[a-zA-Z_ ]*$", RegexOptions.IgnoreCase).Success Then
.
.
.
This is the 'Update' button click.
Here is where i do all the validation for the value in textbox
If errNPassword = False And errCPassword = False And errFirstName = False And errLastName = False And errDob = False And errEmail = False And errNumber = False And errAddress = False Then
conn.Open()
sql2 = "Update [Users] Set password='" & newPassword & "', firstname='" & newFName & "', lastname='" & newLName & "', dob='" & newDob & "', address='" & newAddress & "', email='" & newEmail & "', phone='" & newNumber & "' WHERE username='" & txtUsername.Text & "'"
cmd = New SqlCommand(sql2, conn)
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(String.Format("~/index.aspx?"))
Else
Dim message As String = "Please correct the error above"
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("alert('")
sb.Append(message)
sb.Append("')};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
Exit Sub 'break
End If
This is how i update the value of textbox to my database where the username is match.

Your page is posting back and running the same code, you have to add If Not IsPostBack to Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End If
End Sub

Related

VB.net Input string was not in a correct format

Here is a picture of error
Keep Getting error
input string was not in correct format
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
My guess is the CInt but it works in another similar application . Not sure what is going on . Here is the code
product-detail.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class HTML_Product_Detail
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("ProductID") <> "" Then
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
Dim connProduct As SqlConnection
Dim cmdProduct As SqlCommand
Dim drProduct As SqlDataReader
Dim strSQL As String = "Select * from Product Where ProductID = " & Request.QueryString("ProductID")
connProduct = New SqlConnection(strConn)
cmdProduct = New SqlCommand(strSQL, connProduct)
connProduct.Open()
drProduct = cmdProduct.ExecuteReader(CommandBehavior.CloseConnection)
'drProduct.Read()
If drProduct.Read() Then
lblProductName.Text = drProduct.Item("ProductName")
lblProductDescription.Text = drProduct.Item("ProductName")
lblPrice.Text = drProduct.Item("Price")
lblProductNo.Text = drProduct.Item("ProductNo")
imgProduct.ImageUrl = "images/product-detail/" + Trim(drProduct.Item("ProductNo")) + ".jpg"
End If
End If
End Sub
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' *** get product price
Dim dr As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
strSQLStatement = "SELECT * FROM Product WHERE ProductNo = '" & lblProductNo.Text & "'"
Dim conn As New SqlConnection(strConnectionString)
conn.Open()
cmdSQL = New SqlCommand(strSQLStatement, conn)
dr = cmdSQL.ExecuteReader()
Dim decPrice As Decimal
If dr.Read() Then
decPrice = dr.Item("Price")
End If
conn.Close()
'*** get CartID
Dim strCartID As String
If HttpContext.Current.Request.Cookies("CartID") Is Nothing Then
strCartID = GetRandomCartIDUsingGUID(10)
Dim CookieTo As New HttpCookie("CartID", strCartID)
HttpContext.Current.Response.AppendCookie(CookieTo)
Else
Dim CookieBack As HttpCookie
CookieBack = HttpContext.Current.Request.Cookies("CartID")
strCartID = CookieBack.Value
End If
'Check if this product already exist in the cart
Dim dr2 As SqlDataReader
Dim strSQLStatement2 As String
Dim cmdSQL2 As SqlCommand
strSQLStatement2 = "SELECT * FROM cart WHERE CartID ='" & strCartID & "' and ProductID = '" & Trim(lblProductNo.Text) & "'"
'Reponse.Write(strSQlStatement2)
Dim conn2 As New SqlConnection(strConnectionString)
cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
conn2.Open()
dr2 = cmdSQL2.ExecuteReader()
If dr2.Read() Then
Dim intQuantityNew As Integer = dr2.Item("Quantity") + CInt(tbQuantity.Text)
strSQLStatement = ""
cmdSQL = New SqlCommand(strSQLStatement, conn)
Else
Dim dr3 As SqlDataReader
Dim strSQLStatement3 As String
Dim cmdSQL3 As SqlCommand
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
'Response.Write(strSQLStatement3)
Dim conn3 As New SqlConnection(strConnectionString)
conn3.Open()
cmdSQL3 = New SqlCommand(strSQLStatement3, conn3)
dr3 = cmdSQL3.ExecuteReader()
End If
'Response.Redirect("ViewCart.aspx")
End Sub
Public Function GetRandomCartIDUsingGUID(ByVal length As Integer) As String
'Get the GUID
Dim guidResult As String = System.Guid.NewGuid().ToString()
'Remove the hyphens
guidResult = guidResult.Replace("-", String.Empty)
'Make sure length is valid
If length <= 0 OrElse length > guidResult.Length Then
Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
End If
'Return the first length bytes
Return guidResult.Substring(0, length)
End Function
End Class
The issue is almost certainly here:
CInt(tbQuantity.Text)
The exception information even says:
Conversion from string "" to type 'Integer' is not valid.
You cannot convert a String to an Integer if the text doesn't represent a valid value and an empty string obviously doesn't represent a number. Validate the data first or else validate and convert in one go using Integer.Tryparse.

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

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`

Any possible chance for a memory leak?

i get this error System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException was thrown.` Why?? Kindly help me. I get this error (only when i host the website online, not in local machine).
Dim db As SqlDatabase = Connection.connection
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Dim lblNodeID As Label = CType(Master.FindControl("lblParentId"), Label)
Using conn As DbConnection = db.CreateConnection()
Dim cmdInsertGroup As SqlCommand = db.GetSqlStringCommand("Insert Into CategoryGroups Values ('" & BLL.getNewGroupIDfromCategoryGroups & "','" & lblParentId.Text.Trim & "','" & txtGroupName.Text.Trim & "')")
Try
If fuGroupAttributes.HasFile Then
fuGroupAttributes.SaveAs(IO.Path.Combine(Server.MapPath("~/Admin/SpecificationExcels"), lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName)))
Dim path As String = Server.MapPath("~/Admin/SpecificationExcels/" & lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName))
Dim strmail As String = String.Empty
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";Extended Properties=Excel 12.0;"
Dim objConn As New OleDbConnection(connectionString)
objConn.Open()
Dim strConString As String = "SELECT * FROM [Sheet1$]"
'where date = CDate('" + DateTime.Today.ToShortDateString() + "')";
Dim objCmdSelect As New OleDbCommand(strConString, objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.
Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.
Dim ds As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(ds, "ExcelData")
'My Exp
Dim _newAttributeID As Integer = BLL.getNewAttributeIDfromGroupAttributes
Dim _newGroupID As Integer
conn.Open()
Dim trans As DbTransaction = conn.BeginTransaction()
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
Else
_newGroupID = BLL.getNewGroupIDfromCategoryGroups
db.ExecuteNonQuery(cmdInsertGroup, trans)
End If
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(0) = _newAttributeID
ds.Tables(0).Rows(i).Item(1) = _newGroupID
_newAttributeID = _newAttributeID + 1
Next
' Clean up objects.
objConn.Close()
'Dim db As SqlDatabase = Connection.connection
Dim sqlBulk As New SqlBulkCopy(conn, SqlBulkCopyOptions.Default, trans)
sqlBulk.DestinationTableName = "GroupAttributes"
sqlBulk.WriteToServer(ds.Tables(0))
trans.Commit() ' commit the transaction
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Green
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Successfully Uploaded"
'Response.Redirect("~/Admin/AddSpecifications.aspx?id=" & Request.QueryString(0))
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select an Excel File"
'Response.Write("")
End If
Catch ex As Exception
trans.Rollback() ' rollback the transaction
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Some Error Occured"
End Try
End Using
End Sub
Your code is a bit complicated to follow, but in this block you Exit Sub without closing the connection objConn
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
You should really try to refactor this huge block of code in more small units. In this way you could use the Using statement to dispose correctly of the Disposable objects like OleDbConnection, OleDbAdapter, OleDbCommand....

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