How to remove duplicates in a listbox VB.net - asp.net

I am trying to remove duplicates in a ListBox which is populated by a query pull. I use this code to prevent adding duplicates in VB 6.0 but does not work when converted over to VB.net. Is there a substitute method to prevent or remove duplicates.
colSchema = dr("Col_Schema").ToString
If Not lstSchema.Items.ToString.Contains(colSchema) Then
lstSchema.Items.Add(New ListItem(colSchema))
End If

try
colSchema = dr("Col_Schema").ToString
dim exists as boolean = false
for i as integer = 0 to lstSchema.items.count - 1
if lstSchema.items.item(i) = colSchema then
exists = true
end if
next
if exists = false then
lstSchema.Items.Add(New ListItem(colSchema))
end if

This code
lstSchema.Items.ToString
is converting Items to a string. Items is most likely the type ListBox.ObjectCollection (if this is WinForms) or a similar collection type for other UI frameworks. Calling ToString on such classes will end up calling Object.ToString, which just returns the name of the class.
Instead, try
lstSchema.Items.Contains(colSchema)
If that does not work for some reason, please update your question explaining exactly what you were trying to solve by calling ToString.

Related

Handle Null condition

I want to handle null condition in below code.
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
My code is getting break at
dataSet.Tables("History").Rows(0)("DiscountsAdjustments")
since its value is null. I want to replace null value with "0.00"
Please help how can I handle.
Thanks
Rahul,
You will likely need to rewrite this part of it. Here is your original code:
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
Instead of this big nested mess... why not do it this way. Note I dont have a VB debugger in front of me so there may be some slight format adjustments, so consider this pseudo code:
Is the dataset valid
If Not IsDBNull(dataSet.Tables("History"))
''We know that we have data in our dataset
''Do all your checks
if Not isDBNull(dataSet.Tables("History").Rows(0)("Your field"))
''Do something
Else
''Show a 0
END IF
''REPEAT THE ABOVE LINES FOR EACH FIELD
End if
You can check for null on any column first using methods on the DataRow object:
Which of IsDBNull and IsNull should be used?

need help update a datatable cell value

I have a trivial question about updating a datatable MyDT. I googled and found several approach and got compile errors. Here is the code and here is what I tried with the error. Any help is greatly appreciated. BTW, I am using asp.net framework 2.0 and VB.NET
MyDT.Rows[1][4] = "4NF" ' Property access must assign to the property or use it value
row.Item("New_Column") = "4NF" ' Input string was not in a correct format.
Couldn't store <4NF> in New_Column Column. Expect type is Byte.
row["New_Column"] = "4NF" ' Expression is not a method
Dim StatusCode As String
For Each row As DataRow In MyDT.Rows
StatusCode= row.Item("ThisColumn").ToString()
If StatusCode= "NONF" Then
MyDT.Rows[1][4] = "4NF"
End If
Next row
You should either:
Store data as String in your DataTable
Do a conversion
Here how the conversion looks
MyDT.Rows[1][4] = Convert.ToByte("4NF")

How to select specific index in a multidimensional array in asp.net using vb

I cannot explain well in the title so i'll explain here the scenario:
In here, i have a query that will be placed in an array.
Dim arrUsers As Object = {{sqlReader("dephead"), dropdown1}, {sqlReader("mm"), dropdown2}
I want to enable the dropdown object if it matches my if else condition:
'indexes1= the 1st indexes of each pair in the array (the sqlReaders)
'indexes2= my dropdown objects in my user control
For Each indexes1 In arrUsers
If Session.Item("EmployeeID") = indexes1 Then
indexes2.Enabled = True
End If
Next
so lets say the my session id will be "dephead", then the dropdown1 will be enabled. Thats what i would like to happen but im not familiar on arrays so kindly help me. Thanks.
This should work:
For i As Integer = 0 to arrUsers.GetUpperBound(0)
If Session.Item("EmployeeID") = arrUsers(i)(0) Then
arrUsers(i)(1).Enabled = True
End If
Next
You simply give the array two indexes instead of one. arrUsers(0)(1), for example. The first index returns the object at that index, and the second index returns the object inside the previously returned array. arrUsers(0)(1) will first grab the array at 0 index ({sqlReader("dephead"), dropdown1}), then get the object at index 1 (dropdown1).
This answered my question. The answer above helped me and i just changed the declaration of my arrays and changed some syntax.
Dim arrUsers(,) As Object =
New Object(,) {
{sqlReader("dephead"), dropdown1}, _
{sqlReader("mm"), dropdown2}, _
}
Dim bound0 As Integer = arrUsers.GetUpperBound(0)
Dim bound1 As Integer = arrUsers.GetUpperBound(1)
For i As Integer = 0 To bound0
If Session.Item("EmployeeID") = arrUsers(i, 0) Then
arrUsers(i, 1).Enabled = True
End If
Next

Object Data Source

I'm creating a gridview using an objectdatasource and it works fine when pulling all records. But when I want to use the selectCountMethod the grid shows no values.
I Step through the code and my getInvoices (gets the requested data) returns data and the getInvoicesCount (gets the total record count). But then when I go through the rowdatabound of the gridview there's nothing in there and no data displays.
Here is my code to set the objectdatasource. Any reasons why it wouldn't work or something special that needs to be done for getting the selectcount to work?
Me.ODS.TypeName = "invoice"
Me.ODS.EnablePaging = True
Me.ODS.SelectMethod = "getInvoices"
Me.ODS.SelectCountMethod = "GetInvoiceCount"
Me.ODS.StartRowIndexParameterName = "startRowIndex"
Me.ODS.MaximumRowsParameterName = "maximumRows"
Me.ODS.SelectParameters.Add("strbu", strBusUnit)
Me.ODS.SelectParameters.Add("stremailAddress", emailAddress)
Me.ODS.SelectParameters.Add("startDate", search_startdate)
Me.ODS.SelectParameters.Add("enddate", search_enddate)
Me.ODS.SelectParameters.Add("sortExpression", sortExpression & " " & sortDirection)
With gvInvoices
.PageIndex = intPageIndex
.PageSize = 25
.DataBind()
End With
Check if the count being returned is an integer . debug it . maybe it is null.
and if not null parse it to an integer
I was able to figure this one out. The count was being returned as a long instead of integer. I changed it to integer and all is working great

SelectedValue which is invalid because it does not exist in the list of items

I encounter this problem repeatedly, and haven't a clue what is causing it. I get an exception in the DataBind: SelectedValue which is invalid because it does not exist in the list of items.
Here are some important pieces of information:
I reload listOrgs periodically when the underlying data has changed.
The Organization.DTListAll call returns 2 Int, String pairs.
There are no duplicate or null values in the returned data
After the first two lines below, listOrgs.Items.Count is 0, and the Selected Value is 0
The selected value after the DataBind operation executes is the ID value from the first row in the data
This exception happens the very first time this code is executed after a fresh page load
listOrgs.Items.Clear();
listOrgs.SelectedValue = "0";
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind();
Apparently the solution I posted wasn't entirely effective... Eventually in my application I changed to this:
listOrgs.Items.Clear();
listOrgs.SelectedIndex = -1;
listOrgs.SelectedValue = null;
listOrgs.ClearSelection(); // Clears the selection to avoid the exception (only one of these should be enough but in my application I needed all..)
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind();
I kept getting this error.
Weird thing is that before I set the datasource and rebind after deleting an item the selected index = -1.
If I explicitly set the selectedIndex = -1; then it works and doesn't throw an error.
So even though it was already -1 setting it to -1 stops it from erroring.
Weird eh?
Try setting listOrgs.SelectedValue = "0" after you refresh the DataSource
At the moment you are trying to select the first item in an empty list.
Change the first two line with this :
listOrgs.SelectedItem.Selected = false;
listOrgs.Items.Clear();
In case you still have this problem this is how i resolved it:
listOrgs.SelectedIndex = -1; // Clears the SelectedIndex to avoid the exception
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind(); //Unless you have "listOrgs.AppendDataBoundItems = true" you don't need to clear the list
#PMarques answer helped me out and did solve my problem.
However whilst experimenting, it clicked in my head why I was gettign the error in the first place.
I was setting the "Text" attribute thinking that it might create an encompassing label or fieldset + legend, for me (which it doesn't).
The Text property for a list is infact the SelectedValue property for a ListControl.
So my mistake in misinterpreting what the text property did.
Not sure it is your case, but I had the same problem and apparently there was no explanation, then I realized doing a copy and paste on notepad of a field of database that at the beginning of the value there was a NULL.
Curious thing was that a select joining tables was working. I deleted the row and reinserted, after was working fine.
I was getting the same error repeatedly and try ending up by not setting the default selected value to Index -1.
I commented my code ddlDRIBidAmt.SelectedValue = -1
This value was set at the time where my Page Controls were reset to default values.
I know its too late to answer, but what I tried is an dirty solution but it worked.
After databinding, I am insert a item at index 0
ddl.Items.Insert(0, new ListItem("---Select---","-1"));
And on setting,
I am placing try catch, In catch i am setting Value to -1

Resources