Asp.net VB Test value in GridView - asp.net

I have found heaps of solutions for this in C# but when you are dealing with FindControls and trying to pull a value out of the GridView the C# doesn't help and the translated code doesn't work.
I have this gridview:
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Action Due Date" HeaderText="Action Due Date"
SortExpression="Action Due Date" />
</Columns>
</asp:GridView>
and I have this in vb:
Protected Sub WIPListGrid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DirectCast(e.Row.FindControl("Action Due Date"), Label))
End Sub
Error message is Operator & is not defined for types 'String' and 'System.Web.UI.WebControls.Label'
This is a remedial example of what I ~really~ want to do. Above I just want to display what is contained in DueDate to see what format it is in so I can test it against other values. but it won't work. It appears the the contents of Action Due Date is not a string... so, what am I missing?
I have tried to set the value equal to a string but got the same problem, the Label isn't a string...
How do I find out what's in there in order to evaluate it?
17/01/2013 edit: Keeping this active as I still do not have my issue resolved.
18/01/2013 edit:
vb.net code is now
Protected Sub WIPListGrid_ROWDataBound(sender as Object,
e As System.Web.UI.Webcontrols.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DueDate.Text)
End Sub
But now I get an error that the Object isn't instantiated and its pointing to the msgbox line in the code. I thought that I instantiated it when I dim it as a Label...
The official error is:
"Object reference not set to an instance of an object."
the troubleshooting tips say to
1) Use the "new" keyword to create an object instance
2) Check to determine if the object is null before calling the method
I tried the "new" option and got an error that says the variable has already been declared.
So now I want to check to determine if the object is null and can't figure out how.
I've tried testing: DirectCast(e.Row.FindControl("action due date"), Label) <> ""
but got an error: Overload resolution failed because no accessible '<>' can be called with these arguments.
How do I test to see if the object is null?
The value shouldn't be null (the database doesn't allow it to be null), BUT this could be the crux of my issue...
Any help?

When working with controls, you have to point out that you want that value inside your control.
In your case, you're just going for the label-control itself (not the text inside).
For example:
Dim myControl As Label = DirectCast(e.Row.FindControl("myControl"), Label)
MsgBox("MyText = " & myControl.Text)
Hope this helps.

The problem is you are using a BoundField so there is no control to find. Change it to a templatefield and this will work.
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Action Due Date">
<ItemTemplate>
<asp:Label ID="lblActionDueDate" runat="server" Text='<%# Bind("[Action Due Date]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For Your Row DataBound Event use
Dim DueDateLabel As Label = DirectCast(e.Row.FindControl("lblActionDueDate"), Label)
'Check Label Exists
If DueDateLabel IsNot Nothing Then
Dim DueDateText As String = DueDateLabel.Text
MsgBox(String.Format("Due Date {0}", DueDateText))
End If

Related

How to save a null datetime to SqlServer DB? not working

VS-Studio 2012 Web Express, ASP.NET, WebForms , VB , SqlServer , WebSite application having trouble saving a NULL value for DateTime to the strongly typed ROW:
Dim oRowVEHICLES As Main_TblAdap.tVEHICLESRow = odtVEHICLES.Rows(0) ' (0) is the first row.
oRowVEHICLES.[WElectrical] = If(WElectrical.Year < 10, DBNull.Value, WElectrical)
...etc...
Currently the DetailsView template field textbox is < blank> or empty or "" and the BLL function shows it as a date like: #01/01/0001#. So I test the YEAR value of the passed in variable if less than 10 then save DBNull.Value to the oRowVehicles.[WElectrical] but fails since datatype=Date and cannot convert DBNull to Date.
The DB-field is type Date and allows nulls.
The TableAdapter.xsd view shows the default value is < DBNULL>.
So, why is the oRowVehicles not Date nullable?
How do I make the WElectrical column nullable DATE?
I must be overlooking something, because I cannot be the only one to save an optional DATE value to the Sql-DB.
Your comments and solutions are welcome. Thanks...John
EDIT
ASPX code one DATE field in the DetailsView (others are similar):
<asp:TemplateField HeaderText="Electrical End Date" SortExpression="WElectrical">
<EditItemTemplate>
<TGADate:GADate ID="ucdtWElectrical" runat="server" Enabled="True" MinDate="01/01/1980" MaxDate="12/31/2050"
Caption="Electrical End Date" HideCaption="True" Width="100"
IsRequired="false"
UpdateMode="Conditional"
Text='<%# Bind("WElectrical")%>' />
</EditItemTemplate>
<InsertItemTemplate>
<TGADate:GADate ID="ucdtWElectrical2" runat="server" Enabled="True" MinDate="01/01/1980" MaxDate="12/31/2050"
Caption="Electrical End Date" HideCaption="True" Width="100"
IsRequired="false"
UpdateMode="Conditional"
Text='<%# Bind("WElectrical")%>' />
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="lblWElectrical" runat="server" Text='<%# clsGA_Lib1.fnGetDateTextFromObject(Eval("WElectrical"))%>' Style="font-weight: bold;"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Bold="true" />
</asp:TemplateField>
Object DataSource parameter definition in the ASPX.
<asp:Parameter Name="WElectrical" Type="DateTime" />
BLL Code:
<System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, False)> _
Public Function UpdateFromDetailsView(ByVal original_UID_VEHICLE As Int32, _
ByVal VehicleNbr As String, _
...other function parameter variables...
ByVal WElectrical As Date, _
...other function parameter variables...
) As Boolean
' Get the new VEHICLE-row instance to be updated.
Dim odtVEHICLES As Main_TblAdap.tVEHICLESDataTable = Adapter.GetVhclByVhclID(original_UID_VEHICLE)
If odtVEHICLES.Count <> 1 Then
' no matching record found, return false
Return False
End If
' Populate the values of the ROW.
Dim oRowVEHICLES As Main_TblAdap.tVEHICLESRow = odtVEHICLES.Rows(0) ' (0) is the first row.
With oRowVEHICLES
...setting row-field values...
.[WElectrical] = If(WElectrical.Year < 10, Nothing, WElectrical)
...etc...
End With
' Update the oRowVEHICLES.
Dim rowsAffected As Integer = Adapter.Update(odtVEHICLES)
' Return TRUE if precisely one row was INSERTED, otherwise false.
Return CBool(rowsAffected = 1)
End Function
Edit comment for above code
The WElectrical parameter coming into the BLL-function is a DATE with a value of #01/01/0001#.
The code to place the value into the ROW-object
.[WElectrical] = If(WElectrical.Year < 10, Nothing, WElectrical)
places Nothing as the row-object-field-value.
The Adapter.Update(odtVEHICLES) updates the Sql-DB.
So what is causing the #01/01/0001# value to be placed into the Sql-DB?
Sql-DB column definition
//////// end of Edit ///////////
do one thing:
change DBNull.Value to Nothing
Alternatively you can change the datatype in the dataset to System.Object, and
go to the properties of that data colm
then you can select '(Nothing)' in the dropdown.
set Null value to >> Nothing
Thanks to all commentators to the above question.
The solution is to change the Row-column-variable to this sentence which casts the Nothing to Date? (nullable) as follows...
.[WElectrical] = If(WElectrical.Year < 10, CType(Nothing, Date?), WElectrical)
AND -- Changed the dataset-column-definition (in the .xsd) as follows:
DataType ==> System.Object (not Date)
NullValue ==> (Nothing) (not Throw Exception)
My sincere thanks to all contributors -- since elements of each of their suggestions have contributed to this solution.
This is the solution for sending a nullable value into the DataRow-column.
Thank you for all your help.

ASP:NET - GridVIEW - DropDownList selectedvalue

I am new at this forum though I have passed many years looking for answers into it. Now,I will like your help to solve an issue. I am following this link to make my own DropDown List in my Grid and works fine until this line:
ddlCities.Items.FindByValue(country).Selected = True
here,I have got error:
Object reference not set to an instance of an object.
but my code is right in affected fields:
this is relevant code in Code Behind:
Protected Sub RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso grdLinea.EditIndex = e.Row.RowIndex;
Dim ddlCities As DropDownList = DirectCast(e.Row.FindControl("ddlFacturarA"), DropDownList)
' Create the command with the sproc name and add the parameter required'
ddlCities.DataSource = GetData("select UPPER(DSCA_ZONA)as Zona from tb_personal where dsca_Zona <> 'NULL'group by dsca_zona order by dsca_zona")
ddlCities.DataTextField = "Zona"
ddlCities.DataValueField = "Zona"
ddlCities.DataBind()
'Add Default Item in the DropDownList
'ddlCountries.Items.Insert(0, New ListItem("Please select"))
Dim country As String = Trim(CType(e.Row.FindControl("lblFacturarA"), Label).Text)
ddlCities.Items.FindByValue(country).Selected = True
End If
End Sub
and this is affected code in design mode:
<EditItemTemplate >
<asp:label ID="lblFacturarA" Value ='<%# Eval("facturar_a")%>' Visible ="false" runat="server" />
<asp:DropDownList
ID="ddlFacturarA"
CssClass="txt"
runat="server"
AutoPostBack="True" ValidationGroup="rfNewLineEmpty">
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="rfNewLineFacturarA"
runat="server"
ErrorMessage="Obligatorio"
ValidationGroup="rfNewLine"
SetFocusOnError="True"
ControlToValidate="ddlFacturarA">
</asp:RequiredFieldValidator>
</EditItemTemplate>
I know I am new at ASP.NET and maybe I am loosing something by the way, but I have been round this code for two days and don't see light.
can you tell me something about reason for this error?
please,let me know if you need more detailed information to solve this.
thanks in advance
If you are sure that error is on line ddlCities.Items.FindByValue(country).Selected = True and country item is in dropdown list, I suggest you double check that is there white space or upper/lower case difference in dropdown list item and country variable.
because FindByValue finds exact item and it is case sensitive.
You should try changin query to RTRIM(LTRIM(UPPER(DSCA_ZONA))) as Zona
and
ddlCities.Items.FindByValue(country.ToUpper()).Selected = True
Sorry for delay as I been outside, i think i've solved in this way
Dim country As String = Trim(CType(e.Row.FindControl("lblFacturarA"), Label).Text)
ddlCities.Items.Insert(0, country)
and now it's working fine, Do you think this is a valid way?
many thanks!!!

ASP.NET Losing listbox binding on viewchange?

Ok so what seems like a basic problem is getting the better of me and my exstensive google efforts have come up short. Perhaps I don't understand enough to ask the right questions.
Here's my problem:
I have a formview control, or rather a series of them, each page displaying entry from previous forms, for a higher level access to approve/edit as needed. So, on form "B", I have the contents of form "A" and the blank part of "B" to filled out...So two seperate fromviews on the page.."A" and "B"
That works fine, the issue is when I change the mode to edit previous entry. So if I have a button or the default linkbutton to change from ReadOnly to Edit I not only lose bindings but any efforts to counteract that have left me with issues when I postback.
DUE TO LENGTH I'M LEAVING SOME CODE OUT
On my button I'm using FormView2.ChangeMode(FormViewMode.Edit) to change view, the default link button I've not changed
Bindings on my listboxes are setup like:
If Not Page.IsPostBack Then
'pulling bindings from table
cmd = New OleDbCommand("SELECT * FROM mslToi", objCon)
objReader = cmd.ExecuteReader
lst1.DataValueField = "listing"
lst1.DataTextField = "listing"
lst1.DataSource = objReader
lst1.DataBind()
'pre-selecting input data from form "A"
cmd = New OleDbCommand("SELECT [type_of_injury] FROM S2childToi WHERE ID = " & qs & "", objCon)
objReader = cmd.ExecuteReader
Do While objReader.Read
For Each y As ListItem In lst1.Items
If y.Text = objReader.Item(0) Then
y.Selected = True
End If
Next
Loop
end if
In the page load event.
MARKUP FOR THE FORMVIEW AS ASKED
<asp:FormView ID="FormView2" runat="server"
Width="100%" DataSourceID="AccessDataSource4">
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:FormView>
'''that is the short and sweet of the formview markup as requested. It may also be worth noting that it doesn't matter what mode I start in, if I change modes it equals same result'''
That works fine so far...it's when I change view to Edit that my listbox appears to no longer be bound (controls appear but have no content). My thought is that obviously I'm blocking out my code from postback events (I have a reason for this). I can use this code (without the If Not Page.IsPostBack) to force the selections and bindings but whenever I postback they will defualt to the table data, which can't happen, each listbox needs to postback so I can check for a certain selection. So what happens is the user input is trumped. Short and sweet.
I'm sorry that I can't explain better, any advice is much appreciated. If I can asnwer any questions or post code let me know.
Try this:
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
<asp:ListBox ID="ListBoxReadonly" runat="server"></asp:ListBox>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="ListBoxEdit" runat="server"></asp:ListBox>
</EditItemTemplate>
</asp:FormView>
Then, in your FormView's databound event, bind the data into your listbox depending on the current view.
Protected Sub FormView1_DataBound(sender As Object, e As EventArgs) Handles FormView1.DataBound
Dim myListBox As ListBox
If FormView1.CurrentMode = FormViewMode.ReadOnly Then
myListBox = DirectCast(FormView1.FindControl("ListBoxReadonly"), ListBox)
ElseIf FormView1.CurrentMode = FormViewMode.Edit Then
myListBox = DirectCast(FormView1.FindControl("ListBoxEdit"), ListBox)
End If
If myListBox IsNot Nothing Then
myListBox.DataValueField = "listing"
myListBox.DataTextField = "listing"
myListBox.DataSource = GetListingData()
myListBox.DataBind()
' your pre-select code here...
End If
End Sub

DataFormatString from a dataset, by code

I have selected a bunch of data from my access database which one of the fields is a DateTime field.
I'm trying to show it formated in a GridView but when I try:
dtlJob.DataSource = genericDataSet
dtlJob.Fields(2).DataFormatString = "{0:d}"
dtlJob.DataBind()
I get this error on line 2
Error 2 'DataFormatString' is not a member of 'System.Web.UI.WebControls.DataControlField'.
How do I format my data?
EDIT
This is my DetailsGridView I'm trying t o show off
<asp:DetailsView ID="dtlJob" runat="server" Height="50px" Width="125px">
</asp:DetailsView>
it has nothing but its tags for I'm fetching every data by code from a database. But I want to format the Data Date Field which is appearing like this no more which data it has
You have to create a BoundField like the code below.
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="false" Height="50px" Width="125px">
<Fields>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Birth" HeaderText="Birth" DataFormatString="{0:d}" />
</Fields>
</asp:DetailsView>
I hope that helped.
Vicente
The fields property is readonly, so you can't modify it except in constructor.
Please notice that I have not tested this solution, bt this is what I think you have to do.
So you have to create a new class that inherits from details view and shadows the Fields property, using its own private _fields field:
Imports System.Web.UI.WebControls
Public Class CustomDetailsView
Inherits DetailsView
Private _fields As System.Web.UI.WebControls.DataControlFieldCollection
Public Shadows Property Fields As System.Web.UI.WebControls.DataControlFieldCollection
Get
Return _fields
End Get
Set(ByVal value As System.Web.UI.WebControls.DataControlFieldCollection)
_fields = value
End Set
End Property
End Class
Then you have the following code, creating a CustomDetailsView object, telling it that its datasource is the dataset, formatting the second column field, and giving all hese information to your detaisview on the web form, before binding the data.
Dim myDetailsView = New CustomDetailsView
myDetailsView.DataSource = genericDataSet
CType(myDetailsView.Fields(1), BoundField).DataFormatString = "{0:d}"
dtlJob = myDetailsView
dtlJob.DataBind()
BoundField's base type is DataControlField, so you can write the CType line.
I can't test this right now, please do it and post feedback. If it doesn't work, it could be a beginning of answer.
Greetings
Here is an another solution (still not tested). Here you still make a new class inheriting DetailsView, and you access the fields variable in the constructor:
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Public Class _CustomDetailsView
Inherits DetailsView
Public Sub New(ByVal Columns As List(Of String))
For Each item As String In Columns
Dim bfield As New BoundField
If Not String.IsNullOrWhiteSpace(item) Then
bfield.DataFormatString = item
Else
bfield.DataFormatString = ""
End If
Me.Fields.Add(bfield)
Next
End Sub
End Class
Then, you create a list of string containing the wanted formatting for each column. Then you create your _CustomDetailsView by passing this list of string in the constructor.
Next you assign your DtlJob the _CustomDetailsView object, and finally you provide the datasource and proceed the databinding:
Dim DataFieldStyles = New List(Of String)
' First column: Default style
' Second column: Date format
' Third : Currency Format
' Fourth : Default style
DataFieldStyles.AddRange(New String() {"", "{0:d}", "{0:c}", ""})
Dim My_DetailsView As _CustomDetailsView = New _CustomDetailsView(DataFieldStyles)
dtlJob = My_DetailsView
dtlJob.DataSource = genericDataSet
dtlJob.DataBind()
Same remark as for my other answer, I can't test this, so try it and please give feedback.
Greetings

How to enable a button if regex expression is valid

I have a page on which there are two textboxes that have a regular expression on them.
ASPX Code TextBox 1
<asp:TextBox ID="txtCasesInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCases" ControlToValidate="txtCasesInsert" ValidationGroup="InsertRecord"
runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexCases" ControlToValidate="txtCasesInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
ASPX Code TextBox 2
<asp:TextBox ID="txtPremiumInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPremium" ControlToValidate="txtPremiumInsert"
ValidationGroup="InsertRecord" runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPremium" ControlToValidate="txtPremiumInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
The regular expression works as intended for both text boxes.
What I need now is to be able to check the text being inputted into those text boxes and if the regular expression is valid, then enable my Insert button, otherwise, keep the button disabled.
Insert Button
<asp:Button ID="btnInsertRecord" Width="100px" Height="25px" runat="server" Text="Add Record"
CssClass="buttonBlue" ValidationGroup="InsertRecord" />
The reason I want to do this, is because when the regex has an error, the page still allows the user to insert data so I thought of disabling the button if the regex isn't successfull to prevent this.
I tried this C# If regex doesn't match then do something and I've also read up on Microsofts Regex documentation to learn more about what I can do with Regex's but I haven't found any information related to what I need.
I also tried creating a function with a TextChanged method hooked onto the textboxes but it didn't work. No error messages, just the button wasn't disabling when I inputted a wrong string. That's the problem I'm also having now with my current code. It's like nothing is happening. I've hooked the debugger on the _premiumMatch.Success line but again, nothing is happening, it just lets me proceed. When I created the TextChanged method for my button, I also tried adding it into my Page Load method but that disabled the button straight away.
Current VB Code (Example with one of the text boxes)
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _premiumMatch = _regex.Match(txtPremiumInsert.Text)
If _premiumMatch.Success Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
Not sure what I'm doing wrong. Any suggestions? The above VB code, for now is in my buttons click event but even with an invalid regex, when I click the insert is still performed.
First Edit
Just tried calling the below function in my page load but the button disables straight away and does not become enabled if I input a valid regex. Again, example is for one textbox.
Protected Friend Sub CheckPremium() Handles txtPremiumInsert.TextChanged
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _match As Match = _regex.Match(txtPremiumInsert.Text)
If _match.Success Then
btnInsertRecord.Enabled = True
Else
btnInsertRecord.Enabled = False
End If
End Sub
Second Edit
I have tried the above code and I've activated AutoPostBack on the textbox and still when I type an invalid expression it postbacks and activates my button.
Try this code:
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim FoundMatch As Boolean = _regex.IsMatch(textPremiumInsert.Text)
If FoundMatch = True Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
The code above uses the Regex.IsMatch method to compare the string passed with the regex pattern. It returns true if the string matches the Regex pattern.

Resources