How to split the string and databind to gridview? - asp.net

I need to databind the gridview in which the string come from other system.
The format will like that:
A1|Peter|2011-01-01|2012-03-03|0;A9|Jacky|2011-10-01|2012-09-03|2;B3|Chris|2011-10-01|2012-09-03|2;
| as separator of column
; as separator of next record
Is there any method to do that ?
Thanks.
my code as below:
Sub Call_Payroll(ByVal SNO As String)
Dim theType As String = ""
theType = xxxxxx <- Get from Source
Dim tList = theType.Split(";")
Dim dt As New DataTable
dt = ListToDataTable(tList)
RadGrid_payroll.DataSourceID = ""
RadGrid_payroll.DataSource = dt
RadGrid_payroll.DataBind()
End Sub
Public Shared Function ListToDataTable(Of T)(ByVal list As List(Of T)) As DataTable
Dim dt As New DataTable()
For Each info As PropertyInfo In GetType(T).GetProperties()
dt.Columns.Add(New DataColumn(info.Name, info.PropertyType))
Next
For Each T In list
Dim row As DataRow = dt.NewRow()
For Each info As PropertyInfo In GetType(T).GetProperties()
row(info.Name) = info.GetValue(T, Nothing)
Next
dt.Rows.Add(row)
Next
Return dt
End Function

Related

Using ViewState to apply filters on Listview

I have used ListView Control to gets list of products from database. I also stores result in viewstate . Now to apply filter from checkbox to get refined data I want to know how can I use viewState values?
e.g. If 10 Products found in Music category when page loads. Now if user apply filter(Bluetooth) then only that products should be shown which are in Music & has bluetooth..
Now It is working Like on page load Music category gets fetched Then if I check Bluetooth filter then all bluetooth products comes which are not related to music.
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim pageName As String = Me.Page.RouteData.Values("category").ToString()
if not Me.isPostback Then
Try
query = select * from products where category = '"+pageName+"'
Dim conString As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim con As New MySqlConnection(conString)
Dim cmd As New MySqlCommand(query)
con.Open()
Dim da As New MySqlDataAdapter()
cmd.Connection = con
da.SelectCommand = cmd
Dim dt As New DataTable()
da.Fill(dt)
ViewState("Data") = dt
products.DataSource = dt
products.DataBind()
catHeading.Text = pageName
itemCount.Text = dt.Rows.Count.ToString
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
Filter Apply code
Private Sub priceFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles priceFilter.SelectedIndexChanged
'buildWhereClause()
Dim price As String = priceFilter.SelectedValue.ToString()
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.[Select]((Convert.ToString("category='") & price) + "'")
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Sub
I just want when user apply any filter then it should check from viewstate(Data) rather to entire table.
Save your category in viewstate & on Checked get that category in string & join that string in your query. something like this
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim query As String = "select * from table"
Dim joiner As String = ""
Dim condition As String = String.Empty
Dim whereClause As String = String.Empty
Dim priceCondition As String = String.Empty
Try
Dim category As String = ViewState("Data")
condition = String.Concat(condition, joiner, String.Format("{0}", category))
If joiner = "" Then joiner = ""
joiner = " where "
If Not String.IsNullOrEmpty(condition) Then
whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", condition))
joiner = " and "
End If
'Same way you can apply multiple filters as you want & then get that in one string like below
Dim masterClause As String = String.Empty
masterClause = (query & whereClause)
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(masterClause)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Using
End Using
End Using
End Using
For your filter you could use :
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.Select("category='" & category & "'")
products.DataSource = dr
products.DataBind()
itemCount.Text = dr.Length

How to set selectedvalue of Dropdownlist inside a gridview with data from an SQL query using ASP.NET?

I have a problem when setting the selected value of a dropdownlist inside a gridview with the data from a datatable.
I have an SQL query that selects the data that must be displayed from the dropdownlist. The dropdownlist was already populated. Therefore, the result of the query must be be displayed in the dropdownlist.
I tried below the code, but it returns the same value on each row.
This one is the code for selecting the data from database:
Public Function POPULATE_DROPDOWNLIST(ByVal d_Date As Date, ByVal d_Hour As Integer)
Using con As Odbc.OdbcConnection = New Odbc.OdbcConnection(My.Settings.DB_CONN)
Using cmd As Odbc.OdbcCommand = _
New Odbc.OdbcCommand( _
"SELECT * FROM TBLDATA WHERE D_DATE='" & d_Date & _
"' AND DELIVERY_HOUR='" & d_Hour & "'",
con)
con.Open()
Using dr As Odbc.OdbcDataReader = cmd.ExecuteReader
Dim d_List As New List(Of String)
While dr.Read
d_List.Add(dr("CRITERIA").ToString())
End While
con.Close()
Return d_List
End Using
End Using
End Using
End Function
While this one is my code for populating gridview dropdownlist with the data returned by above function.
Dim dList As New List(Of String)
dList = POPULATE_DROPDOWNLIST(txtdate.Text, DropDownList1.Text)
For Each value In dList
For i = 0 To GridView1.Rows.Count - 1
Dim ddl As DropDownList = _
DirectCast(GridView1.Rows(i).Cells(6).FindControl("dropdowncriteria"), _
DropDownList)
ddl.SelectedValue = value
Next
Next
Try this:
Public Function POPULATE_DROPDOWNLIST(ByVal d_Date As Date, ByVal d_Hour As Integer) As DataTable
Dim dataTable As New DataTable
Using con As New Odbc.OdbcConnection("CS")
Using cmd As New Odbc.OdbcCommand
cmd.CommandText = "QUERY"
con.Open()
Dim dataAdapter As New Odbc.OdbcDataAdapter(cmd.CommandText, con)
dataAdapter.Fill(dataTable)
Return dataTable
End Using
End Using
End Function
Public Sub BIND_DDL()
Dim previousDDLvalue As String = ddl.SelectedValue
Dim dt As New DataTable
dt = POPULATE_DROPDOWNLIST(Now, 24)
With ddl
.Items.Clear()
.DataSource = dt
.DataValueField = "ID"
.DataTextField = "DESCRIPTION"
.DataBind()
.SelectedValue = previousDDLvalue
End With
End Sub

Return DataTable from a Function

I have a Function which returns DataTable Like this (if there are Rows)...
Protected Function getAideData() As DataTable
Dim dt As DataTable = DAL.ReturnData("select * from pg_PersonalInfo P Left Join pg_employeeInterview E on E.sesID = P.sesID ")
If dt.Rows.Count > 0 Then
Return dt
End If
End Function
Then later in my page I accress it like this:
Dim d as datatable = getAideData
Here is my problem: If I have Data in Datatable then I have no problem, however if I dont have any data returned from my method then there is a issue.
I guess my question is, if I have a Function and that cannot return a datatable (no rows), then what should I return from my function? So i can handle the data properly later in my application.
I guess my question is, if I have a Function and that cannot return a
datatable (no rows), then what should I return from my function?
Return Nothing
Protected Function getAideData() As DataTable
Dim dt As DataTable = DAL.ReturnData("select * from pg_PersonalInfo P Left Join pg_employeeInterview E on E.sesID = P.sesID ")
If dt.Rows.Count > 0 Then
Return dt
End If
Return Nothing
End Function
Function GetDataTable(ByVal qry As String) As DataTable
Dim DbCon As New OleDb.OleDbConnection
Try
Dim ConStr As String
ConStr = System.Configuration.ConfigurationManager.AppSettings("ConnCMSTrend").ToString()
DbCon.ConnectionString = ConStr
DbCon.Open()
Dim queryString As String = qry
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(queryString, ConStr)
Dim res As DataSet = New DataSet
adapter.Fill(res)
DbCon.Close()
GetCMSTrend = res.Tables(0)
Catch ex As Exception
DbCon.Close()
End Try
End Function
'Note That you need to add the connection string in the appsettings file. In the above case ConnCMSTrend is the database connection string.

Persisting datatables in viewstate and databinding

I am passing in a start date, an end date, a SQL stored procedure, and a identifying area code into a shared function to populate five declared datatables.
Public Shared Function getNBOCAPData(ByVal startDate As DateTime, ByVal endDate As DateTime, ByVal sp As String, ByVal orgCode As String) As DataTable
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("CancerRegisterConnectionString").ConnectionString.ToString)
Dim sqlCmd As New SqlCommand
getNBOCAPData = New DataTable
Try
SqlConn.Open()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = SqlConn
sqlCmd.CommandTimeout = 300
sqlCmd.CommandText = sp
sqlCmd.Parameters.AddWithValue("#StartDate", startDate)
sqlCmd.Parameters.AddWithValue("#EndDate", endDate)
sqlCmd.Parameters.AddWithValue("#UserOrgCode", orgCode)
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
getNBOCAPData.Load(reader)
Catch ex As Exception
Common.LogError(ex, True)
Finally
SqlConn.Close()
SqlConn.Dispose()
End Try
End Function
The results of this function are then passed into the datatables like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim patiDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATI", Request.QueryString("orgCode"))
Dim tumDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_TUM", Request.QueryString("orgCode"))
Dim surDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_SUR", Request.QueryString("orgCode"))
Dim cheDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_CHE", Request.QueryString("orgCode"))
Dim patDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATH", Request.QueryString("orgCode"))
Dim hidCount As Integer = 0
If patiDataTable.Rows.Count = 0 Then
divPati.Visible = False
hidCount += 1
End If
If tumDataTable.Rows.Count = 0 Then
divTum.Visible = False
hidCount += 1
End If
If surDataTable.Rows.Count = 0 Then
divSur.Visible = False
hidCount += 1
End If
If cheDataTable.Rows.Count = 0 Then
divChe.Visible = False
hidCount += 1
End If
If pathDataTable.Rows.Count = 0 Then
divPath.Visible = False
hidCount += 1
End If
If hidCount = 5 Then
divNoResults.Visible = True
divInstructions.Visible = False
Else
ViewState("patiDataTable") = patiDataTable
ViewState("tumDataTable") = tumDataTable
ViewState("surDataTable") = surDataTable
ViewState("cheDataTable") = cheDataTable
ViewState("pathDataTable") = pathDataTable
End If
End Sub
The databinding is done like this
Public Shared Sub RetRptBySPNBOCAP(ByRef dg As GridView, ByVal dataTable As DataTable)
dg.DataSource = dataTable
dg.DataBind()
End Sub
Then in preparation for the datatables to be sent to an Excel file the data in ViewState is set to a DataTable like this, but the dataTable.Rows.Count() is throwing a NullReferenceException error as though the databind isn't taking place?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cellDate As DateTime = DateTime.MinValue
Dim dataTable As DataTable = Nothing
Dim prefix As String = "Pati_NBOCAP"
Select Case (Request.QueryString("type").ToString)
Case "Pati"
dataTable = ViewState("patiDataTable")
Case "Tum"
dataTable = ViewState("tumDataTable")
prefix = "Tum_NBOCAP"
Case "Che"
dataTable = ViewState("cheDataTable")
prefix = "Che_NBOCAP"
Case "Path"
dataTable = ViewState("pathDataTable")
prefix = "Path_NBOCAP"
Case "Sur"
dataTable = ViewState("surDataTable")
prefix = "Sur_NBOCAP"
End Select
RetRptBySPNBOCAP(Results, dataTable)
Dim rCount As Integer
If dataTable.Rows.Count() > 0 Then
rCount = dataTable.Rows.Count()
End If
End Sub
You must know that viewstate is a per page concept. So if you put data in the viewstate of a particular page you can't retrieve them from another page. Instead of viewstate you can use Session which is the same for all the pages executed within a user session.
Session("patiDataTable") = patiDataTable
Also, viewstate is by default stored client side ans thus is not suitable for large data objects such as datatables.

(ASP.NET) SQL Data Reader returning Null Values

I am connecting to a database and then using an SQLDataReader to parse through those results and then put those results into variables that I can use at a latter time. The problem is that all of my "results.items" are returning null values. The DataReader is however, showing the proper field count when I debug.
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "editPost" Then
'Remove DataGrid'''''''''
GridView1.Visible = False
'''''''''''''''''''''''''
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = GridView1.Rows(index)
Dim ID As String = GridView1.Rows(index).Cells(0).Text
''''''''''''''''''''''''''''''''''''''''CREATE Controls for Placeholder
Dim editEditor As New CuteEditor.Editor
Dim hiddenID As New HiddenField
hiddenID.ID = "hiddenID"
hiddenID.Value = ID
editEditor.ID = "editEditor"
Dim subjectTXT As New TextBox
subjectTXT.ID = "editorSubject"
Dim br As New Literal
Dim submitChanges As New Button
Dim sbjLabel As New Label
submitChanges.ID = "submitChanges"
submitChanges.Text = " Submit Changes "
submitChanges.Height = 40
submitChanges.Width = 300
sbjLabel.Text = "Subject: "
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
editEditor.AutoConfigure = CuteEditor.AutoConfigure.Simple
br.Text = "<br/><br/>"
plcEditor.Controls.Add(hiddenID)
plcEditor.Controls.Add(sbjLabel)
plcEditor.Controls.Add(subjectTXT)
subjectTXT.Width = "100"
subjectTXT.Height = "25"
subjectTXT.CssClass = "editInput"
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(editEditor)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(submitChanges)
submitChanges.OnClientClick = UpdatePost()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim connStr As String = ConfigurationManager.ConnectionStrings("oakfratnewsConnectionString").ConnectionString
Dim nCon As New SqlConnection(connStr)
Dim addCon As New SqlConnection(connStr)
Dim addCom As New SqlCommand("SELECT * FROM [News] WHERE ([ID] = #ID)", addCon)
addCom.Parameters.AddWithValue("#ID", ID)
addCon.Open()
addCom.ExecuteNonQuery()
Dim results As SqlDataReader
results = addCom.ExecuteReader
While results.Read()
Dim editText As String = results.Item("Content")
Dim Subject As String = results.Item("Subject")
editEditor.Text = editText
subjectTXT.Text = Subject
End While
End If
End Sub
Where do you get the ID value?
"addCom.Parameters.AddWithValue("#ID", ID) "
Remove "addCom.ExecuteNonQuery() "
Why using
Dim editText As String = results.Item("Content")
I define before the loop the variable and then read it in this way
Dim editText As String
While results.Read()
editText = results("Content") ' without .items
...
End While

Resources