I can't get the text.contains("9999999") statement to return true. The column with index of 1 has ID#'s. These id's are anchor tagged and I need to remove the tags if the id number is 9999999. Everything else in the main if statement works correctly.
If e.Row.RowType = DataControlRowType.DataRow Then
lDate = e.Row.Cells(8).Text
e.Row.Cells(7).Text = ConvertDate(e.Row.Cells(7).Text, True)
e.Row.Cells(8).Text = ConvertDate(e.Row.Cells(8).Text, True)
If e.Row.Cells(1).Text.Contains("9999999") = True Then
Regex.Replace(e.Row.Cells(1).Text, "</?(a|A).*?>", "")
Dim yoasd As String = e.Row.Cells(1).Text
End If
If e.Row.Cells(8).Text.Trim = "" Or lDate < lToday Then
e.Row.BackColor = Drawing.Color.BurlyWood
End If
End If
I've also tried:
If e.Row.Cells(1).Text = "9999999"
If e.Row.Cells(1).Text.Trim = "9999999"
If e.Row.Cells(1).Text.Contains("9999999") Then
You could try this on your RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
dim toberemoved as string = DataBinder.Eval(e.Row.DataItem, "ColumName")
if toberemoved = "9999999" then
Regex.Replace(e.Row.Cells(1).Text, "</?(a|A).*?>", "")
//Morestuff here
End If
End If
Remember to replace ColumName with the actuall name of the colum
*not tested built from memory.
Related
First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!
My Public Class is Below:
public class GlobalVariable
public shared listbox2Count = listbox2.items.count
public shared containsListbox2Item
End Class
my code where i assign a text item to a variable object:
Public Function getListBoxText()
If ListBox2.Text = "X,Y Coordinate" Then
GlobalVariable.containsListBox2Item = "X,Y Coordinate"
ElseIf ListBox2.Text = "Latitude, Longitude" Then
GlobalVariable.containsListBox2Item = "Latitude, Longitude"
Return Nothing
End Function
My code where i am stuck is below:
Dim dt As New DataTable
dt.Clear()
For i As Integer = 0 To GlobalVariable.listbox2Count - 1
If GlobalVariable.containsListBox2Item(i) = "X,Y Coordinate" Then
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
ElseIf GlobalVariable.containsListBox2Item(i) = "Latitude, Longitude" Then
If (Not dt.Columns.Contains("Latitude")) Then dt.Columns.Add("Latitude")
If (Not dt.Columns.Contains("Longitude")) Then dt.Columns.Add("Longitude")
End If
Next
Dim mr As DataRow
mr = dt.NewRow
mr("X Coordinate") = "203910"
mr("Y Coordinate") = "190280"
mr("Latitude") = "100022"
mr("Longitude") = "201999"
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
I am absolutely not sure whats wrong with this code and if someone can help me or correct it for me would be great help Thanks. I want to add all four columns into the grid view. and then keep adding more and more columns using else if.
Try this, its extensive but it does work, it displays all the values you have on listbox2
Dim i As Integer
Dim dt As New DataTable
Dim Card As String = ""
Dim Geo As String = ""
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text = "X,Y Coordinate" Then
If Card = "ok" Then
Else
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
Card = "ok"
End If
ElseIf ListBox2.Items.Item(i).Text = "Latitude, Longitude" Then
If Geo = "ok" Then
Else
dt.Columns.Add("Latitude")
dt.Columns.Add("Longitude")
Geo = "ok"
End If
End If
Next
Dim mr As DataRow
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(0).ToString.Substring(0, 1)) Then
If dt.Columns.Item(0).ToString = "Latitude" Then
mr = dt.NewRow
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(0).ToString = "X Coordinate" Then
mr = dt.NewRow
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(2).ToString.Substring(0, 1)) Then
If dt.Columns.Item(2).ToString = "Latitude" Then
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(2).ToString = "X Coordinate" Then
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
Dim res As Integer
res = i Mod 2
If res > 0 Or i = ListBox2.Items.Count - 1 Then
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
End If
Next
Simple Form that defines a GridView by using the contents of a ListBox to provide Column Information
Important I've altered the ListBox Values to represent Column Headers. See why below.
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox2" runat="server">
<asp:ListItem Text="X,Y Coordinate" Value="X Coordinate, Y Coordinate" />
<asp:ListItem Text="Latitude, Longitude" Value="Latitude, Longitude" />
</asp:ListBox>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
EmptyDataText="No Data" ShowHeader="true">
</asp:GridView>
</div>
</form>
Code Behind
Public Class WebForm1
Inherits System.Web.UI.Page
' DataTable Name and Application Cache Key
Const DataTableCacheKey As String = "CoordinatesDataTable"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Create the Table and add to Cache, only once
If Not Page.IsPostBack Then
CreateDataTableFromListView()
End If
GridView1.DataSource = Cache(DataTableCacheKey)
GridView1.DataBind()
End Sub
Create the DataSource
NOTE: By using the Value Property of the ListItem as a comma separated list of strings, you can associate multiple columns to a given Coordinate system. Note this is not the ideal way because there is no way set up a data type, I'm assuming everything is a Double value. Still it's far better than a long string of If conditions to determine columns and headers.
' All the magic happens here...
Private Sub CreateDataTableFromListView()
' Instantiate a DataTable with a table name
Dim dt As New DataTable(DataTableCacheKey)
' Loop throught the ListBox and...
For Each li As ListItem In ListBox2.Items
' Split each Value Property into an array
' of strings to use as Column identifiers
Dim ColumnHeaders() As String = li.Value.Split(",")
' Loop through the array of strings to create
' DataTable Columns
For Each ch As String In ColumnHeaders
dt.Columns.Add(ch, GetType(Double))
Next
Next
' Add an initial Blank Row
Dim row As DataRow = dt.NewRow()
' Loop Through Columns and set a default
' value of 0 for each column
For Each c As DataColumn In dt.Columns
row(c.ColumnName) = 0
Next
' Add the Row to the Table
dt.Rows.Add(row)
' Persist the DataTable to the Application cache
Cache(DataTableCacheKey) = dt
End Sub
End Class
Im doing this project for an online test in ASP.NET in VB im using Microsoft visual studios 2012.
Im trying to get a loop going through my textboxes and check them against a word this will be change to be validated against a database to see if the answer are correct but when I do my loop I cannot get my text from the textbox.
Please see below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As Object
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Textboxname
TextboxText = textbox
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
It looks like you are trying to use the string identifier of the control in place of the the actual control. Instead, you should take this identifier and search for the actual control on the page. You can do this using the FindControl method
Your function would therefore look something like (not compile tested):
Private Sub GoGoGo()
'
Dim oTextBox As TextBox
Dim oLabel As Label
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oTextBox = CType(Page.FindControl("TextQ" & CStr(check)), TextBox)
OTextBox.ReadOnly = True;
End If
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oLabel = CType(Page.FindControl("Label" & CStr(check)), Label)
oLabel.Visible = True
End If
If oTextBox.Text = "" Then
oLabel.Text = "no imput"
oLabel.ForeColor = Drawing.Color.Black
End If
If oTextBox.Text = "server" Then
oLabel.Text = "Correct"
oLabel.ForeColor = Drawing.Color.Green
End If
If oTextBox.Text = "Wrong" Then
oLabel.Text = "Wrong"
oLabel.ForeColor = Drawing.Color.Red
End If
Next
End Sub
Some notes:
You don't need all of those variables. Instead, just find the actual controls, and interact with the properties directly - just check the TextBox.Text value when you need to, and set the Label.text property directly. The set is especially important as you want to update the original control property so it is shown on the page.
Similarly, you don't need Number - you can use check as this is your loop counting variable.
Whether you use the + operator or the & operator for string concatenation is up to you. There's already a good question and several answers here.
You also don't need the exit condition for the loop - the loop will exit as soon as you reach MaxTime. If you want it to exit early, just vary your To condition (e.g. Currentloop To MaxTime - 1)
UPDATE:
Page.FindControl will only work with controls that are immediate children of the root element on the page. Instead, you should try calling FindControl recursively. You should also make sure that a control with the id TextQ1 exists - look in the HTML source for the page on the client to make sure a TextBox with this id exists.
There are many examples of this on the net. Here's a VB.Net version (source: http://www.pavey.me/2007/09/recursive-pagefindcontrol-for-vbnet.html) that you can add to your page:
Public Function FindControlRecursive(Of ItemType)(ByVal Ctrl As Object, ByVal id As String) As ItemType
If String.Compare(Ctrl.ID, id, StringComparison.OrdinalIgnoreCase) = 0 AndAlso TypeOf Ctrl Is ItemType Then
Return CType(Ctrl, ItemType)
End If
For Each c As Control In Ctrl.Controls
Dim t As ItemType = FindControlRecursive(Of ItemType)(c, id)
If t IsNot Nothing Then
Return t
End If
Next
Return Nothing
End Function
Your line in the code above would then become:
oTextBox = FindControlRecursive(of TextBox)(Page.Controls(0), "TextQ" & CStr(check))
You'd also need to do the same for the Label control.
It Look like you are using only name istead of textbox try with the code below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As TextBox
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Ctype(Me.Controls(Textboxname), TextBox)
TextboxText = textbox.Text
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
I am trying to to loop through a dataset's value through the rows in a gridview and color in the text if that row matches.
The code below works however whenever I change the page through the PageIndexChanging and this function is ran again, the coloring doesn't work anymore. It still loops through the gridview if there is a match but the effects are not shown.
--variable initialization class instantiation--
--code to connect to db here--
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
Me.MainPageGridView.DataSource = myDataset
Me.MainPageGridView.DataBind()
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
For Each dataRow In myDataset.Tables(0).Rows
thisID = dataRow("ID").ToString
For Each gvRow In Me.MainPageGridView.Rows
If gvRow.Cells(2).Text = thisID Then
For column = 0 To 14 Step 1
gvRow.Cells(column).ForeColor = Drawing.Color.RosyBrown
Next
Exit For
End If
Next
Next
Why don't you use MainPageGridView_RowDataBound event to match the id? I have re-factored your original code to something like below, please check and let me know if it works:
'In DataBind or some other method
'Load(myDataSet)
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
'Load myDatasetNew and bind it to grid
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
Me.MainPageGridView.DataBind()
and perform id matching in
Protected Sub MainPageGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MainPageGridView.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim id As String = DataBinder.Eval(e.Row.DataItem, "ID") 'The name of ID column in "myDatasetNew"
Dim dv As System.Data.DataView = myDataset.Tables(0).DefaultView
dv.RowFilter = "ID = " & id
If dv.Count > 0 Then 'id matches
'Change foreclor of entire row
e.Row.ForeColor = Drawing.Color.RosyBrown
End If
End If
End Sub
You really need to do your data comparison in the GridView.RowDataBound event.
I try to make this gridview sortable, but it simply doesn't work, anyone know why?
Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
sql = sql & "FROM Product "
sql = sql & "WHERE Category = ? "
Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim dad As New OleDbDataAdapter(sql, conn)
dad.SelectCommand.Parameters.AddWithValue("?", CatID)
Dim dtblProduct As New DataTable()
dad.Fill(dtblProduct)
Dim grdProducts As New GridView
grdProducts.ID = "grdProducts"
grdProducts.CellPadding = 5
grdProducts.CellSpacing = 5
grdProducts.GridLines = GridLines.None
grdProducts.AutoGenerateColumns = False
grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
grdProducts.EmptyDataText = "No Products Available."
grdProducts.DataSource = dtblProduct
Dim dataNavigateUrlFields() As String = {"Product_ID"}
Dim blnfirstCol As Boolean = True
Dim strPageResolveURL As String = String.Empty
Dim strLnkSelectText As String = String.Empty
For Each col As Data.DataColumn In dtblProduct.Columns
If blnfirstCol Then
Dim lnkSelect As New HyperLinkField
With lnkSelect
.Text = _strAction
.DataNavigateUrlFields = dataNavigateUrlFields
.DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
End With
grdProducts.Columns.Add(lnkSelect)
blnfirstCol = False
Else
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case "CODE"
.HeaderText = "Code"
.ItemStyle.Width = 100
.HtmlEncode = False
Case "TRADE_NAME"
.HeaderText = "Trade Name"
.ItemStyle.Width = 200
End Select
.DataField = col.ColumnName
.Visible = True
End With
grdProducts.Columns.Add(myBoundField)
End If
Next
grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
grdProducts.DataBind()
It's frustrating!
I think you are not assigning SortExpression property in Columns.
Please check this example for more detail.
In your example, just add
.SortExpression= col.ColumnName
below
.DataField = col.ColumnName
Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.