ASP:NET - GridVIEW - DropDownList selectedvalue - asp.net

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!!!

Related

Asp.net VB Test value in GridView

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

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

DataBinding: 'System.String' does not contain a property with the name 'dbMake'

I am a newbie at ASP.net and after using sqldatasource with a listview to insert and show results from an SQL server db I want to try using the LINQ datasource since it seems to be more flexible in codebehind.
My problem is this: I droped a listview control to the page and I created the Linq datasource in codebehind with vb. the issue that I am having when I ..Select d.columms name i get the error system.string does not contain a property with the name "columname".. if i ommit the column name then its works fine.. the funny part is the d.count works fine but after that i get the error.. please see my code below:
vb code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim rowsCount As Integer
Dim showSearchForm As String
showSearchForm = Request.QueryString("tab")
If showSearchForm = "1" Then
Dim db As New ASPNETDBDataContext()
Dim q = From b In db.PassengerVehiclesTables Select b.dbMake
rowsCount = q.Count
MsgBox(rowsCount)
lvMakes.DataSource = q
lvMakes.DataBind()
PnlPassengerVehiclesSearch.Visible = True
ElseIf showSearchForm = "2" Then
aspx code
<asp:Panel ID="PnlPassengerVehiclesSearch" Visible="false" runat="server">
Search Passenger Vehicles Form.....<br />
<table style="width: 100%; border-style: solid; border-width: 1px">
<tr>
<td>
<asp:ListView ID="lvMakes" runat="server">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</LayoutTemplate>
<ItemTemplate>
<%#Eval("dbMake")%><br />
</ItemTemplate>
</asp:ListView>
</td>
b.dbMake needs to work so that i can use Distinct ,, ia m using asp.net version:3.5 and IIS version 7.0 ..
not sure what i am missing ,, but i did try alot of approaches,,1- checked the web.config file and it seems to have two assemblies and two namespaces for LINQ..2- used different databinding syntaxs,,and i searched a lot for the solution.. the last one i read the person ommited the name of the column,, i thought that wasnt the best solution.. also my dbMake column is comming up in the "intellisence" ..
thank you in advance for your help..
change the following
Dim q = From b In db.PassengerVehiclesTables Select b.dbMake
to
Dim q = From b In db.PassengerVehiclesTables Select New With {b.dbMake}
For further explanation see Select new keyword combination
The reason is because you're selecting dbMake in your query so the return of this line is a collection of strings:
Dim q = From b In db.PassengerVehiclesTables Select b.dbMake
If you change it to this:
Dim q = From b In db.PassengerVehiclesTables Select b
Your Eval will begin to function. It will query a larger data set than you need, but your binding will happen accurately.

Getting edit value from ListView

I'm missing something here, but I've stared at it too long to see it. I've got a simple ListView, with the typical Edit/Update/Cancel buttons. I've got the following set up in my EditITemTemplate when the row goes into edit mode:
<EditItemTemplate>
<asp:Label ID="AccountIdLabel" runat="server" Text='<%#Eval("lan_id")%>' />
<asp:TextBox ID="EmployeeIdTextBox" runat="server" Text='<%#Eval("emp_id")%>' Columns="5" />
</EditItemTemplate>
At this point the user types a value in the EmployeeIdTextBox. When they press Update, it's trying to do the following:
Private Sub ListView_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles EmployeeListView.ItemUpdating
Dim accountId = CType(EmployeeListView.EditItem.FindControl("AccountIdLabel"), Label).Text
Dim employeeId = CType(EmployeeListView.EditItem.FindControl("EmployeeIdTextBox"), TextBox).Text
UpdateMap(accountId, employeeId)
EmployeeListView.EditIndex = -1
GetData()
End Sub
The problem is that "employeeId" is coming back with the original value in the text box, not what the user entered. What am I missing?
UPDATE: Found it. As usual, caused by other code not included here in an effort to ask a simple question. :)
Found it - I had code in the ItemCommand event that was handling other events, but it was doing the GetData() at the end regardless of the command, so basically the data was being refreshed right before the ItemUpdating event fired. I tightened up ItemCommand, and it's now working as expected.
I think this is because the ItemUpdating event fires before the ListView updates the record. You probably want to put this code in the ItemUpdated event instead.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemupdating.aspx

DropDownList SelectedIndex value not updating on AutoPostback

It looks like this question was addressed here, but his solution did not work for me. I am creating a dynamic dropdown menu system that populates a secondary dropdownlist with the results of a query based on the selected item in the first dropdown.
First dropdown getting populated:
Dim db As New linqclassesDataContext
Dim categories = (From c In db.faq_cats)
NewFaqDropDownCategory.DataSource = categories
NewFaqDropDownCategory.DataTextField = "category"
NewFaqDropDownCategory.DataValueField = "category_id"
NewFaqDropDownCategory.DataBind()
Unset(categories)
Unset(db)
Second dropdown getting populated:
Protected Sub NewFaqDropDownCategory_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim temp As Integer = CInt(Val(NewFaqDropDownCategory.SelectedIndex))
MsgBox(theDrop.SelectedValue)
Return
'Dim db As New linqclassesDataContext
'Dim faqs = (From f In db.faqs Where f.category = NewFaqDropDownCategory.SelectedValue)
'NewFaqDropDownList.DataSource = faqs
'NewFaqDropDownList.DataTextField = "question"
'NewFaqDropDownList.DataValueField = "id"
'NewFaqDropDownList.DataBind()
'NewFaqLabel.Visible = True
'NewFaqDropDownList.Visible = True
'Unset(faqs)
'Unset(db)
End Sub
The markup for the first dropdown...
<asp:DropDownList ID="NewFaqDropDownCategory" AutoPostBack="true" runat="server" OnSelectedIndexChanged="NewFaqDropDownCategory_SelectedIndexChanged">
</asp:DropDownList>
And the second...
<asp:DropDownList ID="NewFaqDropDownList" runat="server" Visible="false">
</asp:DropDownList>
No matter what I have tried, I always get "1" (the value of the first item in the second dropdown). The post I referenced earlier said this had to do with AutoPostBack and the server not knowing the list was updated yet.
Can anyone clarify this for me a little more?
Set a break point on the line that reads: NewFaqDropDownCategory.DataBind() and one in your event handler (NewFaqDropDownCategory_SelectedIndexChanged).
I suspect the databind is being called right before your NewFaqDropDownCategory_SelectedIndexChanged event fires causing your selected value to change.
If so, you need either to make sure you only databind if you aren't in the middle of your autopostback or instead of using NewFaqDropDownCategory.SelectedIndex on the first line of your event handler you can cast the sender parameter to a DropDownList and use its selected value.
I had the same problem. Found I forgot to look if I was posting back to the page or not and I was binding my DropDownList control in the Page_Load event of the page.
I had forgot to use:
if (!IsPostBack)
{
.... do databind ....
}
I think there is a bug in your LINQ query for the second drop down box
Dim faqs = (From f In db.faqs Where f.category = NewFaqDropDownCategory.SelectedValue)
Here you are comparing SelectedValue to category. Yet in the first combobox you said that the DataValueField should be category_id. Try changing f.category to f.category_id

Resources