GridView reloads all Record after Row Selection - asp.net

At Page Load, I populate the GridView with records. Then I created a search functionality to search for records. The GridView is actually updating based on the search text. The problem is when I select a row, the GridView shows all the records and not the list based on search.
Here is the code:
Imports MySql.Data.MySqlClient
Public Class Main_Admin
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim myDataSet As DataSet
Dim strSQL As String
'Dim iRecordCount As Integer
myConnection = New MySqlConnection("server=localhost; user id=root; password=admin; database=db; pooling=false;")
strSQL = "SELECT emp_id AS 'Employee ID', emp_sname AS Surname, emp_fname AS 'First Name', emp_mname AS 'Middle Name', tbl_emp_cat.cat_name AS 'Category', nature AS 'Nature of Employment' FROM tbl_employee JOIN tbl_emp_cat ON tbl_employee.emp_cat = tbl_emp_cat.emp_cat;"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
myDataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "mytable")
GridView1.DataSource = myDataSet
GridView1.DataBind()
myConnection.Close()
End Sub
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
e.Row.Cells(0).Width = 100
e.Row.Cells(0).Attributes.CssStyle("text-align") = "center"
e.Row.Cells(1).Width = 100
e.Row.Cells(2).Width = 100
e.Row.Cells(3).Width = 100
e.Row.Cells(4).Width = 100
If (e.Row.RowType = DataControlRowType.DataRow) Then
'e.Row.Attributes("onmouseover") = "this.style.cursor='hand';"
e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"
e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" & Convert.ToString(e.Row.RowIndex))
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.textDecoration='underline';")
'e.Row.Attributes.Add("onmouseout", "this.style.textDecoration='none';")
'e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(Me.GridView1, Page.ClientScript.GetPostBackEventReference(GridView1, e.Row.RowIndex)))
' "Select$" + e.Row.RowIndex.ToString())
End If
End Sub
Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
GridView1.SelectedIndex = -1
End Sub
Private Sub search_Click(sender As Object, e As EventArgs) Handles search.Click
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim myDataSet As DataSet
Dim strSQL As String
'Dim iRecordCount As Integer
myConnection = New MySqlConnection("server=localhost; user id=root; password=admin; database=db; pooling=false;")
strSQL = "SELECT emp_id AS 'Employee ID', emp_sname AS Surname, emp_fname AS 'First Name', emp_mname AS 'Middle Name', tbl_emp_cat.cat_name AS 'Category', nature AS 'Nature of Employment' FROM tbl_employee JOIN tbl_emp_cat ON tbl_employee.emp_cat = tbl_emp_cat.emp_cat WHERE emp_sname LIKE '%" & search_text.Text + "%';"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
myDataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "mytable")
GridView1.DataSource = myDataSet
GridView1.DataBind()
myConnection.Close()
End Sub
End Class

A quick glance at your code shows that you are missing this line in you page load
If Not Page.IsPostBack Then
->put your code here
End if
Your grid view is being refreshed each time on page load wiping off your filtering functionality.Hope this helps.

Related

How to delete a row in gridview that was added dynamically using asp.net and vb.net

I have a gridview. the rows are added dynamically
Protected Sub btnAddCustomer_Click(sender As Object, e As EventArgs) Handles btnAddCustomer.Click
Dim dtSource As New DataTable
dtSource = CType(ViewState("dtSource"), DataTable)
Dim dr As DataRow = dtSource.NewRow()
dr("Id") = DropDownList3.SelectedIndex
dr("Name") = DropDownList3.SelectedItem
dtSource.Rows.Add(dr)
ViewState("dtSource") = dtSource
GridView1.DataSource = dtSource
GridView1.DataBind()
GridView1.HeaderRow.Cells(1).Text = "ID"
GridView1.HeaderRow.Cells(2).Text = "NAME"
End Sub
Each row has a delete image button, and when it is clicked it fires the Code:
Protected Sub GridVeiw1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If ViewState("dtSource") IsNot Nothing Then
Dim dtSource As New DataTable
Dim drCurrentRow As DataRow = Nothing
Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
dtSource = DirectCast(ViewState("dtSource"), DataTable)
If dtSource.Rows.Count > 0 Then
dtSource.Rows.RemoveAt(rowIndex)
drCurrentRow = dtSource.NewRow()
dtSource.AcceptChanges()
ViewState("dtSource") = dtSource
GridView1.DataSource = dtSource
GridView1.DataBind()
End If
End If
End Sub
The delete procedure is not working!!!
Any suggessions Please?
I read the question regarding How to delete a row in GV, but it is not helping because am not deleting from GV but from DataTable that contains the data for the GV

How to sum one column in gridview and show it in a textbox

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM mcbdatabse.subject_enrolled")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End If
End Sub
I have this code for my gridview, I want to total all the units and show it on my textbox;txtTotalUnits Thanks.This is my gridview and textbox
You could add an event handler for the GridView.RowDataBound Event as follows
Dim total as Integer
Sub CustomersGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles CustomersGridView.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
total = total + Convert.ToInt32(e.Row.Cells(the_column_index).Text) .
txtTotalUnits.Text = Convert.ToString(total)
End If
End Sub
More similar examples on MSDN
Use the datasource table, you need using System.Linq;
var result = tbl.AsEnumerable().
Sum(x => Convert.ToDecimal(x["ColumnNameForWhichYouWantSum"].ToString()));
txtTotalUnits.Text = result.ToString();
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM mcbdatabse.subject_enrolled")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Dim total As Integer = 0
For i As Integer = 0 To dt.Rows.Count - 1
Dim drw As DataRow = dt.Rows(i)
Dim units As Integer = CInt(drw("Units")) 'Assuming Units is the column name'
total += units
Next i
txtTotalUnits.Text = total.ToString
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End If
End Sub

ASP.NET Session remains '0'

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

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.

Dynamic gridview columns event problem

i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row.
I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because:
_OnDataBound is not called on every postback (same for _OnRowDataBound)
_OnInit is not possible because the 'Inner table' for the Gridview is added after Init
_OnLoad is not possible because the 'selected' row is not selected yet.
I can add the columns to the dynamic GridView based on my ITemplate class.
But now the button events won't fire.... Any suggestions?
The dynamic adding of the gridview:
Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
Dim g As GridView = sender
g.DataBind()
If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count > 0 Then
Dim t As Table = g.Controls(0)
Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim c As New TableCell
Dim visibleColumnCount As Integer = 0
For Each d As DataControlField In g.Columns
If d.Visible Then
visibleColumnCount += 1
End If
Next
c.ColumnSpan = visibleColumnCount
Dim ph As New PlaceHolder
ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value))
c.Controls.Add(ph)
r.Cells.Add(c)
t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r)
End If
End Sub
Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView
Dim col As Interfaces.esColumnMetadata
Dim coll As New BLL.ViewStmCollection
Dim entity As New BLL.ViewStm
Dim query As BLL.ViewStmQuery = coll.Query
Me._gridStock.AutoGenerateColumns = False
Dim buttonf As New TemplateField()
buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button")
buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button")
buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button")
Me._gridStock.Columns.Add(buttonf)
For Each col In coll.es.Meta.Columns
Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name)
Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name)
Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name)
Dim f As New TemplateField()
f.HeaderTemplate = headerf
f.ItemTemplate = itemf
f.EditItemTemplate = editf
Me._gridStock.Columns.Add(f)
Next
query.Where(query.PnmAutoKey.Equal(PnmAutoKey))
coll.LoadAll()
Me._gridStock.ID = "gvChild"
Me._gridStock.DataSource = coll
AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand
Me._gridStock.DataBind()
Return Me._gridStock
End Function
The ITemplate class:
Public Class QuantityTemplateField : Implements ITemplate
Private _itemType As ListItemType
Private _fieldName As String
Private _infoType As String
Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String)
Me._itemType = ItemType
Me._fieldName = FieldName
Me._infoType = InfoType
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case Me._itemType
Case ListItemType.Header
Dim l As New Literal
l.Text = "<b>" & Me._fieldName & "</b>"
container.Controls.Add(l)
Case ListItemType.Item
Select Case Me._infoType
Case "Button"
Dim ib As New Button()
Dim eb As New Button()
ib.ID = "InsertButton"
eb.ID = "EditButton"
ib.Text = "Insert"
eb.Text = "Edit"
ib.CommandName = "Edit"
eb.CommandName = "Edit"
AddHandler ib.Click, AddressOf Me.InsertButton_OnClick
AddHandler eb.Click, AddressOf Me.EditButton_OnClick
container.Controls.Add(ib)
container.Controls.Add(eb)
Case Else
Dim l As New Label
l.ID = Me._fieldName
l.Text = ""
AddHandler l.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(l)
End Select
Case ListItemType.EditItem
Select Case Me._infoType
Case "Button"
Dim b As New Button
b.ID = "UpdateButton"
b.Text = "Update"
b.CommandName = "Update"
b.OnClientClick = "return confirm('Sure?')"
container.Controls.Add(b)
Case Else
Dim t As New TextBox
t.ID = Me._fieldName
AddHandler t.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(t)
End Select
End Select
End Sub
Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("insert click")
End Sub
Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("edit click")
End Sub
Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim boundValue As Object = Nothing
Dim ctrl As Control = sender
Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer
boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName)
Select Case Me._itemType
Case ListItemType.Item
Dim fieldLiteral As Label = sender
fieldLiteral.Text = boundValue.ToString()
Case ListItemType.EditItem
Dim fieldTextbox As TextBox = sender
fieldTextbox.Text = boundValue.ToString()
End Select
End Sub
End Class
Oh my oh my, I went to MVC, anybody reading this question should do the same :)

Resources