The data table is returning the correct amount of rows/records.But for some reason I can not get my GridView to Render..nothing displays at all...........
EDIT: The GridView returns "RowErorrs" and "Has Errors" columns. but not my data.
Dim ConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("oakfratintdbConnectionString").ConnectionString
Dim Conn As New SqlConnection(ConnString)
Dim cmd As New SqlCommand("SELECT * FROM [OFCInterments]", Conn)
Dim DA As New SqlDataAdapter(cmd)
Dim DT As New DataTable
'WHERE ([FirstName] = #FirstName)
cmd.Parameters.AddWithValue("#FirstName", "Mike")
Try
Conn.Open()
DA.SelectCommand = cmd
DA.Fill(DT)
GridView1.DataSource = DT
GridView1.DataBind()
If DT.Rows.Count > 0 Then
Dim NoResultsText As String = DT.Rows.Count.ToString + " records found."
txtStatys.Text = NoResultsText
txtStatys.Visible = True
End If
Catch ex As Exception
Throw ex
Finally
Conn.Close()
DA.Dispose()
Conn.Dispose()
End Try
The GridView returns "RowErorrs" and "Has Errors" columns. but not my data.
That is not a property of the GridView but of the DataTable.
DataTable.HasErrors property
You can use DataTable.GetErrors() to retrieve a DataTable with all row errrors. Inspect the RowError property of each DataRow and you know the reason for the exception. You can do that all in a debugger quick-watch-window.
A few points you should take into account:
GridView is not dispayed, some possible reasons:
Is the GridView visible at all(and all of it's parents because it inherits the property)?
have you registered the RowDataBound event and an uncaught exception there?
general suggestions:
Don't use a Catch block just to rethrow the exception(even Throw alone would be better since it would keep the stacktrace). Instead don't catch it or do something useful with it(f.e. logging).
use the Using-statement to dispose your ADO.NET objects like the connection(closes it implicitely)
Related
When i watch my website in firebug (net tab),aspx pages are too long to loaded.How can reduce this load time?. this page is a text and image only and has a little DB query.
this my code:
Public Function SelectForShow() As DataTable
Try
Dim query As String = "SELECT TOP 10 * FROM Tbl_News WHERE NewsConfirm ='True' ORDER BY NewsID DESC "
Using sqlcon As New SqlConnection(ConnectionString)
Dim sqlAdapter As New SqlDataAdapter(query, sqlcon)
Dim Dt As New DataTable()
sqlAdapter.Fill(Dt)
Return Dt
Catch ex As Exception
Throw ex
End Try
End Function
and get data in repeater
I have a dropdownlist which I constantly use.
I wrote a method to load this dropdown.
Though when I call the method only the Text part of the item is passed.
This is the method
Public Shared Function ddlLoadResumes() As DropDownList
Dim connString As String = ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString
Dim conn As SqlConnection = New SqlConnection(connString)
Dim ddSelectResumeList As New DropDownList
Dim dtResumes As New DataTable()
Dim comm As SqlCommand = New SqlCommand("usr_SelectResumeList", conn)
comm.CommandType = CommandType.StoredProcedure
comm.Parameters.Add("#UserName", SqlDbType.VarChar, 50).Value = Membership.GetUser().UserName
Try
Dim daResumes As New SqlDataAdapter(comm)
conn.Open()
daResumes.Fill(dtResumes)
ddSelectResumeList.DataSource = dtResumes
ddSelectResumeList.DataTextField = "ResumeName"
ddSelectResumeList.DataValueField = "Res_ID"
ddSelectResumeList.DataBind()
' Handle the error
Catch ex As Exception
Finally
conn.Close()
End Try
Return ddSelectResumeList
End Function
and this is how I call it
ddSelectResume.DataSource = MailClass.ddlLoadResumes.Items
ddSelectResume.DataBind()
Dim ltitem As ListItem
For Each ltitem In ddSelectResume.Items
Response.Write(ltitem.Value + "-----" + ltitem.Text)
Next returns only the text part
I need both DataTextField and DataValueField.
Thank you in advance
This seems like kind of an odd approach. One thing to resolve your issue would be to just set the ddSelectResume equal to the DropDownList object your Function is returning:
ddSelectResume = MailClass.ddlLoadResumes
Dim ltitem As ListItem
For Each ltitem In ddSelectResume.Items
Response.Write(ltitem.Value + "-----" + ltitem.Text)
Next
Though I think a better approach would be to just have "ddlLoadResumes return the DataTable (dtResumes), and set that as the datasoure of ddSelectResumes (you'd still have to set the DataTextField and DataValueField properties).
How do you rebind the data in Gridview to show 50 and up instead of 1 and up.
Starts from 1:
Dim connStr, cmdStr As String
Dim myDataSet As New DataSet
Dim dt As New DataTable()
connStr = "connection string works"
cmdStr = "SELECT * FROM table1;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using myDataAdapter As New SqlDataAdapter(cmd)
myDataAdapter.Fill(myDataSet)
dt = myDataSet.Tables(0)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
What do I need to change to start from 50 and up?
Make your DataTable an enumerable object and then use LINQ's .Skip() function to get past the first 50 items, like this:
Dim filteredSet = dt.AsEnumerable().Skip(50)
Now bind the filteredSet instead of dt to the grid view, like this:
GridView1.DataSource = filteredSet
GridView1.DataBind()
I would say the most efficient choice would be to not select the data from the database by using a parametrized query where you pass in a starting value of some sort and the query only selects data occurring after this point.
Another option, which only takes a small adjustment to your code is to simply delete rows from the DataTable like so:
' remove the first 50 rows
For x As Integer = 1 To 50
dt.Rows.RemoveAt(0)
Next
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.
I've seen a couple example of how to do this by placing all the code in the aspx file, but I'm trying to do it from the code-behind. Here's what I have in the code behind:
Dim dt As New DataTable
Using conn As New OleDbConnection(ConnectionString)
conn.Open()
Dim dtAdapter As New OleDbDataAdapter
Dim command As New OleDbCommand("SELECT * FROM table " & _
"" _
, conn)
dtAdapter.SelectCommand = command
dtAdapter.Fill(dt)
conn.Close()
End Using
GridView1.DataSource = dt
GridView1.DataBind()
I'm open to any solutions, but I would prefer to do it in the code-behind if possible since thats how the rest of app is. I dont need to necessarily use a gridview just display some tabular data, so whatever works is fine. Im trying to avoid manually constructing sql strings. Any thoughts?
I don't see the question. If you don't kno how to filter the records in your query, use the Where clause with a parameter:
Dim dt = New DataTable()
Using conn As New OleDbConnection(ConnectionString)
Dim queryString As String = "SELECT * FROM Table WHERE Field1 LIKE ?"
Dim command As OleDbCommand = New OleDbCommand(queryString, conn)
command.Parameters.Add("#p1", OleDbType.Char, 3).Value = "a%"
Using da = New OleDbDataAdapter(command)
' you don't need to open/close a connection if you use DataAdapter.Fill
da.Fill(dt)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
DataAdapter Parameters
Using Statement