Adding row in asp.net table - asp.net

I have the following code in my .aspx file
<asp:Table ID="tabStudent" runat="server"></asp:Table>
I declared all variables which I used below. I wrote the following code snippet in the page load event. But it only shows only one row which having last row in my database. But when I am using message box inside this while loop to print those values I am getting all the rows.
Reader = Command.ExecuteReader()
While Reader.Read()
lblRollNo.Text = Reader.Item(0)
lblName.Text = Reader.Item(1)
lblDob.Text = Reader.Item(2)
tcRollNo.Controls.Add(lblRollNo)
tcName.Controls.Add(lblName)
tcDob.Controls.Add(lblDob)
TableRow.Cells.Add(tcRollNo)
TableRow.Cells.Add(tcName)
TableRow.Cells.Add(tcDob)
tabStudent.Rows.Add(TableRow)
End While
what is wrong with this code?

You are not creating new controls in the loop but you're always reusing the same.
While Reader.Read()
TableRow = New TableRow()
lblRollNo = New Label()
tcRollNo = New TableCell()
' and so on ...
lblRollNo.Text = Reader.Item(0)
lblName.Text = Reader.Item(1)
lblDob.Text = Reader.Item(2)
tcRollNo.Controls.Add(lblRollNo)
tcName.Controls.Add(lblName)
tcDob.Controls.Add(lblDob)
TableRow.Cells.Add(tcRollNo)
TableRow.Cells.Add(tcName)
TableRow.Cells.Add(tcDob)
tabStudent.Rows.Add(TableRow)
End While

Related

How to find the value of a dropdownlist using FindControl?

I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.
The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.
I have set the ID's of each DropDownList like so:
FrequencyList.ID = String.Concat("FreqList", DBReader(0))
That is in a loop while reading the DatabaseReader.
This is what I'm having issues with (please note I simplified the code down to make it easier to read:
Dim i As Integer
DBCommand = New SqlCommand()
DBCommand.Connection = DBConnection
DBCommand.CommandType = Data.CommandType.StoredProcedure
DBCommand.CommandText = "StoredProcedureName"
DBConnection.Open()
For i = 1 To AspectTableLength
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
ParamFrequencyID.Direction = ParameterDirection.Input
Next
The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.
I got help from a developer.
Dim MyControls As ControlCollection = Panel.Controls
Dim Number As Integer 'this is the same as "DBReader(0)"
For Each MyControl As Control In MyControls
If MyControl.ID Is Nothing Then
Else
If MyControl.ID.StartsWith("Span") Then
Number = Replace(MyControl.ID, "Span", "")
Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = Freq.SelectedIndex
ParamFrequencyID.Direction = ParameterDirection.Input
DBCommand.ExecuteNonQuery()
DBCommand.Parameters.Clear()
End If
End If
Next
DBConnection.Close()

Load results of LINQ join into datatable (VB.NET)

I've seen a few examples of what I'm trying to do shown in C# but none in VB.NET. When I try to replicate the C# examples in VB the syntax doesn't work.
I've got two datatables that I've loaded. I need to join them into a third datatable. Here's my code:
Dim foxproDataTable As New Data.DataTable = GetDataTable1() 'Load table 1 from a SQL Server db
Dim sqlServerDataTable As New Data.DataTable = GetDataTable2() 'Load table 2 from a Foxpro db
Dim joinedData = From sql In sqlServerDataTable.AsEnumerable()
Join fox In foxproDataTable.AsEnumerable()
On sql.Field(Of Integer)("SqlUserId") Equals fox.Field(Of Integer)("FoxUserId")
Select New With
{
.firstName = fox.Field(Of String)("FirstName"),
.lastName = fox.Field(Of String)("LastName"),
.userId = fox.Field(Of Integer)("foxUserId"),
.address1 = sql.Field(Of String)("Address1"),
.address2 = sql.Field(Of String)("Address2")
}
'load result datatable
Dim result As New Data.DataTable
result.Columns.Add("UserId")
result.Columns.Add("FistName")
result.Columns.Add("LastName")
result.Columns.Add("Address1")
result.Columns.Add("Address2")
Dim newRow As DataRow
For Each row In joinedData
With result
newRow = result.NewRow
newRow("UserId") = row.userId
newRow("FistName") = row.FistName
newRow("LastName") = row.LastName
newRow("Address1") = row.Address1
newRow("Address2") = row.Address2
.Rows.Add(newRow)
End With
Next
When it hits the For Each row In joinedData line, it throws a "Specified cast is not valid" exception. If I set a breakpoint on the line and hover over joinedData, Intellisense identifies its type as "In-Memory Query". I've tried change it to For Each row In joinedData.ToList() but get the same exception.

itextSharp null value showing &nbsp

I am using iTextSharp to create a pdf from a gridview. When there is a null value in the table the pdf places a &nbsp in its place. How do I remove this and show the null value? I do know the pdf is created after the gridview is already populated however is there a way to tell it that nulls should show as blanks? My code is as follows:
Protected Sub btnPDF_Click(sender As Object, e As System.EventArgs) Handles btnPDF.Click
Dim pdfTable As New PdfPTable(grdResults.HeaderRow.Cells.Count)
For Each headerCell As TableCell In grdResults.HeaderRow.Cells
Dim font As New Font()
font.Color = New BaseColor(grdResults.HeaderStyle.ForeColor)
Dim pdfCell As New PdfPCell(New Phrase(headerCell.Text, font))
pdfCell.BackgroundColor = New BaseColor(grdResults.HeaderStyle.BackColor)
pdfTable.AddCell(pdfCell)
Next
For Each gridViewRow As GridViewRow In grdResults.Rows
For Each tableCell As TableCell In gridViewRow.Cells
Dim font As New Font()
font.Color = New BaseColor(grdResults.RowStyle.ForeColor)
Dim pdfCell As New PdfPCell(New Phrase(tableCell.Text, font))
pdfCell.BackgroundColor = New BaseColor(grdResults.RowStyle.BackColor)
pdfTable.AddCell(pdfCell)
Next
Next
Dim pdfDocument As New Document(iTextSharp.text.PageSize.A4, 10.0F, 10.0F, 10.0F, 10.0F)
pdfDocument.SetPageSize(PageSize.A4.Rotate())
PdfWriter.GetInstance(pdfDocument, Response.OutputStream)
pdfDocument.Open()
pdfDocument.Add(pdfTable)
pdfDocument.Close()
Response.ContentType = "application/pdf"
Response.AppendHeader("content-disposition", "attachment, filename-results.pdf")
Response.Write(PdfDocument)
Response.Flush()
Response.End()
End Sub
The values that I was receiving the &nbsp in the pdf came from calculated fields. When there was no value for the calculation it would not put anything in the gridview cell so in turn it would put the blank space value in the pdf. I went back to the calculations and if a value was not determined than I placed a space for the value. For instance -
If dtRaw.Rows(0).Item("ParameterName").ToString() <> "NOY" Then
drCalcRow("NAAQGreater") = iNAAQS
drCalcRow("NAAQGreater80") = iNAAQS80
Else
drCalcRow("NAAQGreater") = " "
drCalcRow("NAAQGreater80") = " "
End If
It works however it adds a lot to the code. It would be nice to have something one time that would check when it loops through the rows as it writes the pdf. I have tried a couple of things but nothing worked or even made an impact.

Find nested gridview in user defined function

I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

Resources