Hi guys I have a question. Is there some way to populate a gridview in asp.net without using a database? I'm using a gridview to show information but I've seen that everytime I try to insert more rows to the grid the last row is changed with a new one and overwrites the data
I'm using the following code:
Dim dtsetinform As New DataSet
Dim datatableinfo As New DataTable("fill")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dtsetinform.Tables.Add(datatableinfo )
gridfactura.DataSource = datatableinfo
datatableinfo.Columns.Add("Name") '
datatableinfo.Columns.Add("Quantity")
datatableinfo.Columns.Add("Price")
Session("fill") = datatableinfo
End Sub
Public Sub agregarfilas(ByVal total As Integer)
datatableinfo = Session("fill")
Dim row As DataRow = datatableinfo .NewRow
row("Name") = ddserviciotxt.Text
row("Quantity") = cantidadtxt.Text
row("Price") = total
datatableinfo .Rows.Add(row)
ViewState("tablainViewState") = datatableinfo
datatableinfo .AcceptChanges()
gridfactura.DataSource = datatableinfo
gridfactura.DataBind()
End Sub
Protected Sub btnagregar_Click(sender As Object, e As EventArgs) Handles btnagregar.Click
Dim result As Integer
Dim price As Integer = preciotxt.Text
Dim quantity As Integer = cantidadtxt.Text
result = price * quantity
agregarfilas(result)
End Sub
you need to put the code in the page load in
if not Page.IsPostBack then
your code
end if
Related
I am using ASP.NET with VB.NET and I want the user add several row to data table.
I am trying to add multi row into data table in run time by (textboxes, rad combo box and check box).
I add first row second and third row.
But when I present the data table its show only the last row I enter
so the table contain only one row.
How do I keep all row in data table not only one row? I tried everything please help.
This is my code:
Dim dcItemID = New DataColumn("ItemID", GetType(Int32))
Dim dcUnit = New DataColumn("UnitID", GetType(Int32))
Dim ItemPrice = New DataColumn("ItemPrice", GetType(Int32))
Dim sellprice = New DataColumn("SellPrice", GetType(Int32))
dt.Columns.Add(dcItemID)
dt.Columns.Add(dcUnit)
dt.Columns.Add(ItemPrice)
dt.Columns.Add(sellprice)
dt.Rows.Add(Convert.ToInt32(rcItemName.SelectedValue), Convert.ToInt32(rcUnitID.SelectedValue), tbItemPrice.Text, tbSellprice.Text)
thank u all i found the answer
if any one interested this is my solution :
Public Class WebForm1
Inherits System.Web.UI.Page
Private dt As DataTable = New DataTable()
Private dr As DataRow = Nothing
Protected Sub btnSaved_Click(sender As Object, e As EventArgs) Handles btnSaved.Click
If ViewState("table") IsNot Nothing Then
dt = CType(ViewState("table"), DataTable)
End If
dr = dt.NewRow()
dr("ItemPrice") = tbItemPrice.Text
dr("SellPrice") = tbSellprice.Text
' dr("Product_Amount") = txtAmount.Text
dt.Rows.Add(dr)
ViewState("table") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ItemPrice")
dt.Columns.Add("SellPrice")
End Sub
End Class
Index was out of range. Must be non-negative and less than the size of the collection.This error is showing if I change the page number in grid view.In first page every rows are working correctly but after first page if I click on any row it is showing the error.
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
For Each row As GridViewRow In GridView_modify.Rows
If row.RowType = DataControlRowType.DataRow Then
row.Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
row.Attributes("onmouseout") = "this.style.textDecoration='none';"
row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(GridView_modify, "Select$" & row.DataItemIndex, True)
Next
MyBase.Render(writer)
End Sub
Protected Sub GridView_modify_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_modify.SelectedIndexChanged
PanelModify.Visible = True
connection.ConnectionString = connectionstringdb
Try
connection.Open()
Dim row As GridViewRow = GridView_modify.SelectedRow
test1 = DirectCast(GridView_modify.SelectedRow.Cells(1).FindControl("HiddenField1"), HiddenField).Value
lbl_slno.Text = test1
selectAllFieldsUpdate()
txt_tenderDate_update.Text = GridView_modify.SelectedRow.Cells(2).Text ' or 'Text1.Value = row.Cells[1].Text;
txt_sub_update.Text = GridView_modify.SelectedRow.Cells(1).Text
txt_lastdate_udpate.Text = GridView_modify.SelectedRow.Cells(3).Text
Catch ce As Exception
Response.Write(ce.ToString())
Finally
connection.Close()
End Try
connection.Close()
End Sub
Protected Sub GridView_modify_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_modify.PageIndexChanged
Filldatagrid()
End Sub
Protected Sub GridView_modify_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView_modify.PageIndexChanging
GridView_modify.PageIndex = e.NewPageIndex
End Sub
Public Sub Filldatagrid()
connection.ConnectionString = connectionstringdb
Try
connection.Open()
Dim strsql1 As String = ("SELECT SlNo,Subject,convert(varchar(10),[TenderDate],105) as TenderDate,convert(varchar(10),[Lastdate],105) as Lastdate,Filename from TenderTable order by convert(datetime, Tenderdate, 105) Desc")
Dim mydatadapter As New SqlDataAdapter(strsql1, connection)
Dim mydataset As New DataSet
mydatadapter.Fill(mydataset, "TenderTable")
GridView_modify.DataSource = mydataset.Tables("TenderTable")
GridView_modify.DataBind()
connection.Close()
Catch ex As Exception
Response.Write(ex.ToString())
connection.Close()
End Try
End Sub
I've been reading posts and articles and just getting a little confused and consequently burning through time I don't have at the moment
Can someone look at my code and tell me where I've gone wrong?
Partial Class PayerContacts
Inherits System.Web.UI.Page
Dim connStrDRContacts As String = ConfigurationManager.ConnectionStrings("DRContacts_SQL").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
navBuild()
End Sub
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack Then
LoadContacts(ViewState("objSender"))
End If
End Sub
Private Function navBuild() As Integer
Dim SQLstrDRs As String = "SELECT * FROM DRList"
Dim DbConnDRs As SqlConnection = New SqlConnection(connStrDRContacts)
DbConnDRs.Open()
Dim dtDRsTemp As New DataTable
Dim SQLAdapterDRs As New SqlDataAdapter(SQLstrDRs, DbConnDRs)
SQLAdapterDRs.Fill(dtDRsTemp)
'Loop through each row of the DataView to create HTML table data
Dim NewTableRow As New TableRow
For Each row As DataRow In dtDRsTemp.Rows
'CREATE table with button to display contacts related to client (one to many)
Dim NewTableButton As LinkButton = New LinkButton
NewTableButton.ID = "btnDRName" & NewTableText
NewTableButton.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler NewTableButton.Click, AddressOf LoadContacts
Next
Return 0
End Function
Protected Sub LoadContacts(sender As Object, e As EventArgs)
Dim LoopCount As Integer = 0
Dim SQLstrLoadTable As String = "SELECT * FROM ContactList WHERE DRVendor = '" & sender.Text.ToString & "'"
and so on....
SQLAdapterLoadTable.Fill(dtLoadTableTemp)
Dim NewTableRow As New TableRow
For Each row As DataRow In dtLoadTableTemp.Rows
'CREATE Accordion to display data
NewAccordion.ID = "ContactAccordion" & LoopCount
NewAccordion.Visible = True
blah, blah...
'SET Pane
NewAccordionPane.HeaderContainer.ID = "PaneHeader" & LoopCount
NewAccordionPane.ContentContainer.ID = "PaneContent" & LoopCount
'CREATE button to open ModalPopup to EDIT each record
Dim imgGear As New ImageButton
imgGear.ID = "btnGear" & row!ID.ToString
imgGear.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler imgGear.Click, AddressOf EditRecord
'LOAD Pane
NewAccordionPane.HeaderContainer.Controls.Add(NewHeaderTable)
NewAccordionPane.ContentContainer.Controls.Add(New LiteralControl(NewTableText))
ViewState("objSender") = sender
End Sub
Protected Sub EditRecord(ByVal sender As Object, ByVal e As EventArgs)
'Open ModalPopup to edit record
popup.Show()
pnlAddEdit.Visible = True
End Sub
End Class
The Infinities Loop articles on ViewState and Dynamic Controls should really be read by every Webforms developer: -
http://mocha.mojoskins.com/SharedFiles/Download.aspx?pageid=566&mid=786&fileid=38
http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_
The examples are in C# but you should be able to figure out what's going on, it's the same base class library after all.
I have a Gridview filled by a dataTable, filled by a DataAdapter. That's how grid is initially loaded in Page_Load.
To add a search funcionality, I make the same but passing TextBox.Text as parameter to the SELECT... LIKE ... statement.
To add an edit funcionality(a button in every row) I need the previous data in the dataTable, and if I performed a search before editing I need only the result of the search in my dataTable.
The problem is, I don't know how to keep its value alive (persistent), and dataTable has 0 columns when I press teh edit button, so it doesn't display anything to edit.
I guess it happens because I'm using Using, and dataTable is probably getting cleaned after End Using.
In that case, whta can I do to fix it? I thought removing miconn.Close() but it doesn't solve anything, in fact, I don't know if connection is still open after End Using.
Code:
Dim con As New Connection
Dim table As New DataTable()
Private Sub fill_grid()
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
fill_grid()
End If
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim miCon As New Connection
Using miconn As New SqlConnection(miCon.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA WHERE area LIKE #area"
Using command As New SqlCommand(sql, miconn)
command.Parameters.Clear()
command.Parameters.Add("#area", SqlDbType.VarChar).Value = "%" + TextBox1.Text + "%"
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = table
GridView1.DataBind()
End Sub
Protected Sub CancelEditRow(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
GridView1.DataSource = table
GridView1.DataBind()
End Sub
BindGrid()
{
var dt = YourMethodReturningDatatable();
ViewState["Table"] = dt;
grid.DataSource = ViewState["Table"];
grid.Databind();
}
page_load
{
if(not ispostback) // not because my 1 key stopped working.
{
BindGrid();
}
}
I would suggest you to make two different functions for filling the data table and binding it. Call the filling function before the !IsPostBack condition and do the binding inside the condition. Here is the sample code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim table as new DataTable
table = GetData() 'The function that would return a data table
If Not IsPostBack Then
GridView1.DataSource = table
GridView1.DataBind()
End If
End Sub
Private Function GetData() As DataTable
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GetData = table
miconn.Close()
End Using
End Using
End Using
End function
Hope it helps.
I have a button which is not created dynamically. When I click on that button the number of lines in a textbox are counted. I store that in the variable called count. Depending on value of count I create buttons in panel.
Up to now it is working properly.
Now the click event of those buttons is not firing.
I have tried to google my question. But everywhere I got the same answer. Create the controls in Page_Init event. But how is it possible? I am getting the value of count from a textfile's lines, and that value of count decides how many button will be created in the panel.
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
btnAllowList.Add(btnAllow)
tdAllow.Controls.Add(btnAllow)
The code for btnAllow_Click
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For x As Integer = 0 To btnAllowList.Count - 1
If sender.ID.SubString(3) = btnAllowList(x).ID.Substring(3) Then
Dim lineCount = IO.File.ReadAllLines(PendingRequestsPath).Length
Dim reader As New System.IO.StreamReader(DocumentViewersPath)
Dim allLines As New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Dim DocumentViewerAlreadyExists As Boolean = False
For i As Integer = 0 To lineCount - 1
If ReadLine(i, allLines) = lblRequestorsList(x).Text Then
DocumentViewerAlreadyExists = True
Exit For
End If
Next
If DocumentViewerAlreadyExists = False Then
Dim Writer As System.IO.StreamWriter = IO.File.AppendText(DocumentViewersPath)
Writer.WriteLine(lblRequestorsList(x).Text)
End If
Dim line As String = ""
Dim r As IO.StreamReader = IO.File.OpenText(PendingRequestsPath)
Dim strFile As New ArrayList
While r.Peek <> -1 ' Loop through the file
line = r.ReadLine 'Read the next available line
' Check to see if the line contains what you're looking for.
' If not, add it to an ArrayList
If Not line.Contains(lblRequestorsList(x).Text) Then
strFile.Add(line)
End If
r.Close()
' Because we want to replace the content of the file, we first
' need to delete it.
If IO.File.Exists(PendingRequestsPath) Then
IO.File.Delete(PendingRequestsPath)
End If
' Create a StreamWriter object with the same filename
Dim objWriter As New IO.StreamWriter(PendingRequestsPath, True)
' Iterate through the ArrayList
For Each item As ArrayList In strFile
objWriter.WriteLine(item) ' Write the current item in the ArrayList to the file.
Next
objWriter.Flush()
objWriter.Close()
End While
End If
Next
End Sub
This worked for me:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim NumberOfControls As Integer = 10
Session("CreateControls") = NumberOfControls
End Sub
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'This will be executed when clicking on the newly created buttons.
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("CreateControls") IsNot Nothing Then
For x As Integer = 0 To Convert.ToInt32(Session("CreateControls"))
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
Panel1.Controls.Add(btnAllow)
Next
End If
End Sub