VB - Gridview style after index changed - vb.net

i've a gridview with pagesize=10, when i load the page and bind grid i've the correct style applied (checkbox cheched or no), but when i go to second page i can't apply the style (checkbox always not checked) and if i came back to the first page i haven't the correst style applied.
At the page load i store all checkbox states into a dictonary to check when i bind the grid.
Public listaCheckbox As New Dictionary(Of Integer, Boolean)
I tried to apply a style to the first row to understand where I'm wrong but it's always the same thing.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RecuperaCheckbox() 'to store all checkbox value into listaCheckbox, it works
If IsPostBack = False Then
Me.BindGrid2()
End If
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles GridViewListaEsp.PageIndexChanging
GridViewListaEsp.PageIndex = e.NewPageIndex
Me.BindGrid2()
End Sub
Private Sub BindGrid2()
Query = "SELECT ...
FROM ...;"
List.SelectCommand = Query
GridViewListaEsp.DataBind()
For i = 0 To GridViewListaEsp.Rows.Count - 1
Dim chk As CheckBox = GridViewListaEsp.Rows(i).FindControl("chkOnOff")
Dim id_azienda As String = GridViewListaEsp.Rows(i).Cells(1).Text
listaCheckbox.TryGetValue(id_azienda, chk.Checked) 'works only at the first page load
Next
GridViewListaEsp.Rows(0).Attributes.Add("style", "background-color:aqua") 'works only at the first page load
End Sub

I found the solution:
to bind grid i used the command:
list.SelectCommand = Query
this was working for all thing except for the application of the style after index changing.
I changed part of code with this:
cmdExist = New SACommand(szPrintf(Query), con)
drExist = cmdExist.ExecuteReader
Dim DT As New DataTable
DT.Load(drExist)
GridViewListaEsp.DataSource = DT
GridViewListaEsp.DataBind()
And now i can apply new style after change index page!

Related

OnSelectedIndexChanged no working in aspx Page

i have this dropdownlist in my page
<asp:DropDownList ID="ddlselectTaxas" runat="server" AutoPostBack="True" CssClass="form-control" OnSelectedIndexChanged="ddlselectTaxas_SelectedIndexChanged"
EnableViewState="True" ViewStateMode="Enabled"></asp:DropDownList>
and this is the function in the vb file
Public Sub ddlselectTaxas_SelectedIndexChanged(sender As Object, e As EventArgs)
taxas.TryGetValue(ddlselectTaxas.SelectedItem.Text, valorTxt.Text)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
End Sub
I want to change the value of a textbox (valorTxt) when I select a diferent value in the dropdownlist, but the function is not firing. I dont know why, i have zero experience with VB and asp pages. I apreciate your help. thanks in advance.
EDIT
here is the full code of the page
Public Class Emitir
Inherits System.Web.UI.Page
Public taxas As New Dictionary(Of String, String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
CarregaValores()
valorTxt.ReadOnly = True
End If
End Sub
Private Sub CarregaValores()
Dim dt As DataTable
Dim objAcesso As New AcessoBD
Dim consulta As String = "SELECT TE.COD_TAXA, TE.DESC_TAXA, TV.VL_TAXA FROM TAXAS_EXPEDIENTE TE JOIN TAXAS_EXPEDIENTE_VALOR TV ON TE.COD_TAXA = TV.COD_TAXA"
dt = objAcesso.DataTable(consulta, CommandType.Text)
For Each linha As DataRow In dt.Rows
taxas.Add(linha.ItemArray(1), linha.ItemArray(2))
Next
valorTxt.Text = dt.Rows.Item(0).ItemArray(2)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
ddlselectTaxas.DataTextField = "DESC_TAXA"
ddlselectTaxas.DataValueField = "COD_TAXA"
ddlselectTaxas.DataSource = dt
ddlselectTaxas.DataBind()
End Sub
Protected Sub ddlselectTaxas_SelectedIndexChanged(sender As Object, e As EventArgs)
taxas.TryGetValue(ddlselectTaxas.SelectedItem.Text, valorTxt.Text)
valorTxt.Text = valorTxt.Text.Substring(0, valorTxt.Text.Length - 2)
End Sub
End Class
You don't show your code to load up the drop list.
Remember, your page load code fires EVERY time on post back.
So, if in code on page load, you load up the drop list? You need to do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
LoadCal()
End If
End Sub
Sub LoadData()
Dim cmdSQL As New SqlCommand(
"SELECT ID,(FirstName + ' ' + LastName) as EmpName
FROM Employee ORDER BY FirstName")
lstEmployee.DataSource = MyRstP(cmdSQL)
lstEmployee.DataBind()
End Sub
Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Now, in above, I was using a listbox, but they work the same as a drop down list (combo box).
but, if you do NOT place the loading up of data inside of the If Not IsPostBack?
Then what happens is you select a drop down, and say click on a button (or in your case autopostback = true, then the page load FIRES FIRST and THEN your code runs!!!
and, if your code re-loads the drop list? Then your selection is lost!!!
So, for just about ANY page you create, ALWAYS, but always use the is postback code stub in on-load - and thus your loading of controls data ONLY occurs one time. Since if you re-load every time, then you lose your changes.
Well, I am not sure of what was happening, but I remade my page and it is working now. something was blocking the event. Thanks for your help.

VB.NET DataSet table data empty

I'm trying to use the dataset for a report, but the data is gone when I try to use it. Here is my code for the most part:
Variables:
Dim ResultsDataView As DataView
Dim ResultsDataSet As New DataSet
Dim ResultsTable As New DataTable
Dim SQLQuery As String
Search:
This is where a datagrid is populated in the main view. The data shows up perfectly.
Private Sub Search(Optional ByVal Bind As Boolean = True, Optional ByVal SearchType As String = "", Optional ByVal SearchButton As String = "")
Dim SQLQuery As String
Dim ResultsDataSet
Dim LabelText As String
Dim MultiBudgetCenter As Integer = 0
SQLQuery = "A long and detailed SQL query that grabs N rows with 7 columns"
ResultsDataSet = RunQuery(SQLQuery)
ResultsTable = ResultsDataSet.Tables(0)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
sb.Append(item.ToString + ","c)
Response.Write(item.ToString + "\n")
Response.Write(vbNewLine)
Next
sb.Append(vbCr & vbLf)
Next
'Response.End()
If Bind Then
BindData(ResultsDataSet)
End If
End Sub
Binding Data:
I think this is a cause in the issue.
Private Sub BindData(ByVal InputDataSet As DataSet)
ResultsDataView = InputDataSet.Tables("Results").DefaultView
ResultsDataView.Sort = ViewState("SortExpression").ToString()
ResultsGridView.DataSource = ResultsDataView
ResultsGridView.DataBind()
End Sub
Reporting action:
This is where I am trying to use the table data. But it is showing as nothing.
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
The reason I'm trying to loop through this data is to both display the data in a gridview on the main view as well as export the data to CSV. If there is a different way to export a SQL query to CSV, I'm open to any suggestions.
There has to be something I can do to get the data from the SQL query to persist through the ReportButton_Click method. I've tried copying the datatable, I've tried global variables, I've tried different methods of looping through the dataset. What am I missing?!
Thank you all in advance.
EDIT
Here is the Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
'set focus to postback control
Dim x As String = GetPostBackControlName(Page)
If Len(x) > 0 Then
x = x.Replace("$", "_")
SetFocus(x)
End If
End If
If Not IsPostBack Then
ResultsGridView.AllowPaging = False
'Enable Gridview sorting
ResultsGridView.AllowSorting = True
'Initialize the sorting expression
ViewState("SortExpression") = "ID DESC"
'Populate the Gridview
Search()
End If
End Sub
In your search function add this line after the ResultsTable setting
ResultsTable = ResultsDataSet.Tables(0)
Session("LastSearch") = ResultsTable
Then in your report click event handler recover your data from the Session variable
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
ResultsTable = DirectCast(Session("LastSearch"), DataTable)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
You need to read about ASP.NET Life Cycle and understand that every time ASP.NET calls your methods it creates a new instance of your Page class. Of course this means that global page variables in ASP.NET are not very useful.
Also consider to read about that Session object and not misuse it.
What is the difference between SessionState and ViewState?

Add data into new added row in `DataGridView` from `DataBindingSource`

In Form4 i have a DataGridView named DbTableDataGridView.
In Form3 there is a set of fields (text boxes) that are all bound to the DbTableBindingSource . When I run application the Form4 shows up. There is a button to open new form (Form3) and in there enter details about customers to be added as new row into database (DataGridView). My code for the "Add" button in Form4 looks like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.DbTableDataGridView.Refresh()
Me.DbTableBindingSource.AddNew()
Form3.ShowDialog()
Form3.ImiéTextBox.Text = ""
Form3.NazwiskoTextBox.Text = ""
Form3.Numer_TelefonuTextBox.Text = ""
Form3.Numer_RejestracyjnyTextBox.Text = ""
Form3.MarkaTextBox.Text = ""
Form3.ModelTextBox.Text = ""
Form3.Poj_SilnikaTextBox.Text = ""
Form3.RocznikTextBox.Text = ""
Form3.PaliwoTextBox.Text = ""
Form3.Data_PrzyjeciaDateTimePicker.Value = DateTime.Now
Form3.RichTextBox1.Text = ""
End Sub
It does add new row, selects it and clears entries in the text boxes (that are bound into 'DbTableBindingSource'.
In this form after I fill in all the fields I press button save:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Validate()
Form4.DbTableBindingSource.EndEdit()
Me.DbTableTableAdapter.Update(CartronicDBDataSet.dbTable)
TableAdapterManager.UpdateAll(CartronicDBDataSet)
DbTableTableAdapter.Fill(Form4.CartronicDBDataSet.dbTable)
MsgBox("Saved")
Catch ex As Exception
MessageBox.Show("Blad zapisu. Sprobuj ponownie. W razie potrzeby zamknij, a nastepnie uruchom ponownie program Cartronic")
End Try
End Sub
It goes to the message "Saved" but actually does not fill in added new recently.
Any thoughts?
There is no link that I can see between Form3 and your data.
I'd recommend passing the newly created data row to a new instance of Form3.
Get the reference to your newly added row
Create a new Form3 (avoid default instance forms, they're ugly and evil). This will mean you don't need to clear the textboxes as you have a brand new form every time.
Pass the datarow into your form where you will bind it directly to the textboxes
Dim newRow = CType(Me.DbTableBindingSource.AddNew(), DataRow)
Using frmEditor As New Form3
frmEditor.DataSource = newRow
frmEditor.ShowDialog()
End Using
In form3 add the property (or preferably a constructor)
Private mDataSource As DataRow
Public Property DataSource As DataRow
Get
Return mDataSource
End Get
Set(value As DataRow)
mDataSource = value
Me.ImiéTextBox.DataBindings.Add("Text", mDataSource, "ImiéFieldName")
' ....
End Set
End Property
If you use this approach then you can get rid of all of the textbox clearing code.
I have done what you have suggested but little bit simpler.
Assigned all text boxes to each cell in current row as follows:
Form4.DbTableDataGridView.CurrentRow.Cells(5).Value = Me.NazwiskoTextBox.Text.ToString
Form4.DbTableDataGridView.CurrentRow.Cells(4).Value = Me.ImiéTextBox.Text.ToString
It works fine.
Cheers

Button Array - how to pass a parameter to shared handler

I have a bit of code where i have a dynamically created array or buttons with staff pictures on them, as well as the staff's name. I've added one handler to handle any button click from any of the buttons. where i am stuck is, if you look at the code below, it all works fine, and if you click any of the buttons you get the "aha" test message. but i want the name of the staff clicked on (so btnArray(i).Text) to be passed to the handler for further processing. I tried adding a ByVal parameter to the handler but that caused an error. what's the correct way to do this? As i said, the code below works for me, i just am at a loss as to how to add the extra functionality.
Dim btnArray(staffcount) As System.Windows.Forms.Button
For i As Integer = 1 To staffcount - 1
btnArray(i) = New System.Windows.Forms.Button
btnArray(i).Visible = True
btnArray(i).Width = 80
btnArray(i).Height = 101
btnArray(i).BackgroundImage = Image.FromFile(picloc(i))
btnArray(i).BackgroundImageLayout = ImageLayout.Stretch
btnArray(i).Text = staffname(i)
Dim who As String
who = btnArray(i).Text
AddHandler btnArray(i).Click, AddressOf Me.theButton_Click
btnArray(i).ForeColor = Color.White
btnArray(i).TextAlign = ContentAlignment.BottomCenter
Dim fnt As Font
fnt = btnArray(i).Font
btnArray(i).Font = New Font(fnt.Name, 10, FontStyle.Bold)
FlowLayoutPanel1.Controls.Add(btnArray(i))
Next i
End Sub
Private Sub theButton_Click()
MsgBox("aha")
End Sub
First, correct the signature of your shared handler.
Private Sub theButton_Click(sender As Object, e As EventArgs)
End Sub
Once that is done getting the text of the button clicked is a simple matter.
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim textOfButtonClicked As String = DirectCast(sender, Button).Text
MessageBox.Show(textOfButtonClicked)
End Sub
The sender is the button that was clicked. Since signatures use objects for the sender the DirectCast 'changes' it to button and you then can access the .Text property of the button.
If there are more manipulations you want to perform on the clicked button you could do it this way
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim whBtn As Button = DirectCast(sender, Button) ' get reference to button clicked
Dim textOfButtonClicked As String = whBtn.Text
MessageBox.Show(textOfButtonClicked)
'e.g. change the color
whBtn.BackColor = Color.LightYellow
End Sub

get value of selected item in second column... returning previous item

I get that there are other questions like this, but for some reason nobody seems to have this problem. I'm trying to populate a 2 column listview that I create on load like this.
With lstShipMethods
.View = View.Details
.FullRowSelect = True
.HeaderStyle = ColumnHeaderStyle.None ' set to whatever you need
.Columns.Clear() ' make sure collumnscollection is empty
' Add 3 columns
.Columns.AddRange(New ColumnHeader() {New ColumnHeader(), New ColumnHeader()})
End With
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data1"}))
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data2"}))
It populates just fine, but when I try to get the data from the selected items column like this
Private Sub lstShipMethods_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstShipMethods.SelectedIndexChanged
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End Sub
after the first click it will always show both values aka second column from row one and row two will be output in the MessageBox.
You can use the ItemSelectionChanged event instead.
Private Sub lstShipMethods_SelectedIndexChanged(sender As System.Object, e As ListViewItemSelectionChangedEventArgs) Handles lstShipMethods.ItemSelectionChanged
If e.IsSelected Then
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End If
End Sub