I have the following procedure, which works fine. The only part that I am having an issue with is when the CompNames list has more than 1 record. I am trying to use String.Join with vbCrLf but it doesnt work.
Anyone have any ideas or an alternative I could use.
Public Sub gvTeamList_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim TeamID As Integer
If e.Row.RowType = DataControlRowType.DataRow Then
TeamID = DataBinder.Eval(e.Row.DataItem, "TeamID")
Dim sSQL As String
sSQL = "SELECT C.CompetitionName, CTT.TeamID " & _
"FROM tblCompetition C " & _
"left join tblCompetitionToTeam CTT on C.CompetitionID = CTT.CompetitionID " & _
"left join tblTeam T on CTT.TeamID = T.TeamID " & _
"where CTT.TeamID = " & TeamID
Dim dr = DataClass.GetDataReader(sSQL)
Dim bRows As Boolean = dr.HasRows
Dim CompNames As New List(Of String)
While dr.Read
CompNames.Add(dr("CompetitionName"))
End While
Dim Name As String
If CompNames.Count > 0 Then
For Each Name In CompNames
e.Row.Cells(5).Text = String.Join(vbCrLf, CompNames.ToArray)
Next
End If
'e.Row.Cells(5).Text =
e.Row.Cells(5).ForeColor = Drawing.Color.Yellow
e.Row.Cells(5).BackColor = Drawing.Color.DarkBlue
dr.Close()
End If
End Sub
I have also tried Environment.NewLine and that doesnt work either
It appears you are using a WebForms application. In HTML, a line return generally has no effect because whitespace is ignored (unless it's embedded in certain tags). You want to use <br /> to generate a line break:
e.Row.Cells(5).Text = String.Join("<br />", CompNames.ToArray)
Also, you don't need the For Each loop, because String.Join enumerates the entire array in a single call. It's redundant to run this once for each Name in CompNames.
Related
Currently in my Web form I have a cascading drop down list, but I'm focusing on the 1st drop down list for now.
Here is the code to load the list.
Private Sub FillLine() ' load 1st dropdown data
Dim dt As New DataTable
Dim strSql = "select distinct level1_id, [LCODE1]+ ' | '+[LNAME1] as [LCODE1]" _
& " FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP]"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
line.DataSource = dt
line.DataTextField = "LCODE1"
line.DataValueField = "level1_id"
line.DataBind()
line.Items.Insert(0, "")
End If
End Sub
And here is the visual representation of how the data I'm pulling looks like.
| level1_id | LCODE1 |
-----------------------------
| 1 | A01 | Line 1 |
I also want to have the drop down list auto load in the correct value based on URL query string.
My plan is to 1st load the value in an invisible textbox, and instruct drop down list to select the same data based on that textbox using page load event.
'load textbox with query string info
Sub loadFrmQuery()
Dim LID As String = Request.QueryString("LID")
Dim cmd As New SqlCommand("SELECT level1_id " _
& ", level2_id " _
& ", level3_id " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] " _
& "where [LEVEL3_ID] = '" & LID & "'", conn)
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
While rdr.Read
line_text.Text = rdr("level1_id")
process_text.Text = rdr("level2_id")
equip_text.Text = rdr("level3_id")
End While
conn.Close()
End Sub
'page load event
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("EmpID") Is Nothing Then
Response.Redirect("~/Login.aspx")
Else
If Not IsPostBack Then 'whenever hv dropdownlist, need to have this in load sub, or else won't get ddl data.
FillLine()
loadFrmQuery()
line.DataValueField = line_text.Text
End If
End If
End Sub
But during testing, the drop down list won't load in data. I tried calling out the DataTextField and DataValueField of the drop down list and still no response. What should I do in this case?
Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)
It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?
When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]
Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.
I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.
I get a catch exp as Exception Error in which says, data source is an invalid type, it must either be of the type IListSource, IEnumerable or IDataSource.
This error comes when I try to add a new record to a database through a gridview, so I get the data from database nicely into this gridview, therefore I do not understand that I get a catch exp as exception when the database is not unavailable.
The #thesli_number OleDbType.VarChar Value = thenumber is type of number in the db.
'Add new record to DB
Protected Sub AddNewTask(ByVal sender As Object, ByVal e As EventArgs)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("txttestcat"), TextBox).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("txttestinfo"), TextBox).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("txttestnumber"), TextBox).Text
Dim strSQL As String = ""
strSQL = "" & _
"INSERT INTO [TableTest] " & _
"([test_cat], [test_info], [test_number])" & _
"VALUES (#thesli_cat, #thesli_info, #thesli_number)"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.VarChar).Value = thenumber
GridView1.DataSource = cmd
GridView1.DataBind()
'MsgBox("Row(s) Added !! ")
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
EDIT................EDIT.................EDIT...................EDIT
Ok i can now add data to the gridview, i can delete a record and i can add a new record.
But i cant get the update event to work, can u see whats wrong in this new code !?
'Update record
Protected Sub UpdateTask(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim theid = Convert.ToInt32(DirectCast(GridView1.FooterRow.FindControl("lbltestid"), Label).Text)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("lbltestcat"), Label).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("lbltestinfo"), Label).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("lbltestnumber"), Label).Text
Dim strSQL As String = ""
strSQL = "" & _
"UPDATE [TableTest] " & _
"SET [test_cat] = #thesli_cat, [test_info] = #thesli_info, [test_number] = #thesli_number " & _
"WHERE [test_id] = #thesli_id"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_id", OleDbType.Integer).Value = theid
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.Integer).Value = thenumber
cmd.ExecuteNonQuery()
'MsgBox("Row(s) Updated !! ")
GridView1.EditIndex = -1
GetRecords()
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
If the answer to your original question was answered in my comment above (posted below here in quotes), then you should mark this question as answered, then post an entirely new question so you get more accurate responses. This question no longer applies to your actual problem.
My answer which, in your comment, solved your original question:
That example (referring to the link in your comment above) does not directly assign an
OleDbCommand to the DataSource, because it
can't. If you look at the example the author passes the cmd variable
to the GetData function GetData(cmd), which more than likely executes
the stored procedure and returns a DataSource supported type (e.g.
IListSource, IEnumerable or IDataSource).
I want to populate the dropdownlist ddVerantwortlich1 with the people with the proper credentials based on the selected process step ddProzessschritt1
It doesn't work if I want to change it using datasource and databind
i have to manually loop through the table in the dataset returned from the query. then it works. but not otherwise...
What's the problem? Here my code:
Protected Sub ddProzessschritt1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddProzessschritt1.SelectedIndexChanged
'StefanSteiger.Debug.MsgBox("index changed!")
Dim dsProcessResponsibleDataSet As Data.DataSet = New DataSet
Dim strSQL As String = "SELECT BE_ID, (BE_Name + ' ' +BE_Vorname) as UserName FROM T_Benutzer WHERE BE_ID IN "
strSQL += "(SELECT BEBG_BE FROM T_Benutzer_Benutzergruppen WHERE BEBG_BG IN "
strSQL += "(SELECT ZO_BG_ID FROM T_DMS_ZO_Prozesse_Berechtigungen WHERE ZO_PROC_UID = '" + ddProzessschritt1.SelectedValue.ToString + "')) ORDER BY UserName"
If StefanSteiger.DBcmds.GetDataSet(strSQL, dsProcessResponsibleDataSet) > 0 Then
Me.ddVerantwortlich1.Items.Clear()
For Each row As Data.DataRow In dsProcessResponsibleDataSet.Tables(0).Rows
'StefanSteiger.Debug.MsgBox(row("UserName").ToString + " ¦ " + row("BE_ID").ToString)
ddVerantwortlich1.Items.Add(New ListItem(row("UserName"), row("BE_ID")))
Next
'Me.ddVerantwortlich1.Dispose()
'Me.ddProzessschritt1.DataSource = dsProcessResponsibleDataSet.Tables(0)
'Me.ddVerantwortlich1.DataTextField = "UserName"
'Me.ddVerantwortlich1.DataValueField = "BE_ID"
'Me.ddVerantwortlich1.DataBind()
Else
'Me.ddProzessschritt1.Dispose()
ddVerantwortlich1.Items.Add(New ListItem("Niemand verantwortlich.", Nothing))
End If
End Sub
Why you call Dispose on the DropDown? Maybe that's the problem. Give it a try!