DetailsView Insert default value for checkboxes - asp.net

I have a big DetailsView form for an insert to a database and I have a lot (10+) checkbox fields. Many of them aren't visible because we don't want those fields activated yet to have data submitted (but may be activated in the future).
How I can set the default value of all checkboxes at first to "false" (unchecked)? As of right now, they are being inserted as nulls and that doesn't play too well with everything else.
So far I have this code behind running as an onDataBound event for the DetailsView:
Dim row As DetailsViewRow
For Each row In DetailsView1A.Rows
If row.Cells.GetType() = GetType(CheckBox) Then
Dim tempCheckbox As CheckBox = CType(row.Cells(1).Controls(0), CheckBox)
If tempCheckbox Is DBNull.Value Then
tempCheckbox.Checked = False
End If
End If
Next
However, all the checkboxes are still being submitted as nulls. What am I doing wrong?

Try handling the ItemInserting event, and updating the "Values" collection of the DetailsViewInsertEventArgs object. These are the values that will be passed to your datasource's insert statement.
Go through and update the "Values" entry for each of these hidden CheckBox columns to False. Here's is an example:
Sub CustomerDetail_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs)
e.Values("yourFieldName") = False
End Sub
Note that "yourFieldName" will be the name of the column in the datasource to which the DetailsView is connected.
Also, False might need to be a string, I'm not sure how this actually gets passed:
e.Values("yourFieldName") = "False"
One other thought: if the above doesn't work (for some reason those hidden CheckBoxes don't have entries in the Values collection), I would just not hide them on the server side - hide them using CSS or JavaScript. In other words, instead of having Visible="False" on your CheckBox, use the CSS property display:none.

Related

Casting a control to another page

I have tried everything to no avail. I need to cast the value from a user selected dropdownlist to another dropdownlist on another page. The data in the textboxes are a series of numbers.
Also is there a way to display the value in the second dropdown list as well as other values? For example, my dropdown has the values 1-6, user selects 4, which displays first in the dropdown on page 2 but the other values also display in case they want to change there selection??
If Not Page.PreviousPage Is Nothing Then
Dim table As Control = PreviousPage.Controls(0).FindControl("table1")
Dim ddl As DropDownList = CType(table.FindControl("ddlB_Codes"),c DropDownList)
If Not ddl Is Nothing Then
ddl_OC.DataSource = ddl.SelectedValue.Substring(0, 6)
End If
End If
Quick update I FINALLY got my casting to work through a session, only now I need to know how to display the session values and the other additional values for my drop box in case the user wants to change something? Thanks for the help
ddl_OC.DataSource = CType(Session.Item("valCodes"), String)
ddl_OC.DataBind()
ddl_SO.DataSource = CType(Session.Item("valAccts"), String)
ddl_SO.DataBind()
Use event selectedvaluechanged to set datasource for another DropDownList, when first one is changed.
Don't forget to populate it vin DataBind function usage.

when using datasource and databind to set items in a dropdownlist - index is always the value of first item

I am trying to use datasource and bind in my application to set a dropdown list to the results of a query. The dropdownlist populates correctly (shows each different type_name in the set) but later when I use ddltype.selectedvalue - I am always getting the value from the first item in the dataset. Here is the code.
if ds.hasRows = true
ddlType.DataValueField = "type_id"
ddlType.DataTextField = "type_name"
ddlType.DataSource = ds
ddlType.DataBind()
end if
Then later on I use the following code to try to get teh selected value
Dim typeID = ddlType.SelectedValue
I have ran the query to get the dataset on my SQL server and get the below results - but every time I use the above dim statement, the value is set to 812 even when type 2 is selected. Below is the results from the query that fills the sqldatareader named ds.
type_id : type_name
___________________
812 : type one
813 : type two
Thanks in advance.
Based on the information in your question, I don't see anything wrong.
But based on common mistakes people make with this pattern, I am guessing you are probably running ddlType.DataBind() on every postback. So the user clicks a button or something similar to fire the postback, and the DDL is re-bound before your click handler checks the value. Re-binding sets the selectedvalue back to default.
Edit: Your databinding code in Page_Load should only run once. One way to do this is to wrap the databinding code...
If Not IsPostBack Then
If ds.hasRows = True Then
ddlType.DataValueField = "type_id"
ddlType.DataTextField = "type_name"
ddlType.DataSource = ds
ddlType.DataBind()
End If
End If
This will cause the databinding to occur only the first time the page is requested, but not after a button click or other postback action.

Pre-Select Items in a dynamically populated CheckBoxList

I've been experimenting with this and trying to understand the Page Life Cycle for hours upon hours. I'm completely stumped at this point :'( Any help would be GREATLY appreciated.
Below are my methods. My _PrefillWizard method actually works for all the controls on my page except for those which are dynamically populated. The CheckBoxLists are such because they are automatically generated based on selectable values in a table in my DB. I already have this control in my markup like so... how do I force this to load and be ready before running my other code?
<asp:CheckBoxList ID="MyLanguagesCBL" runat="server" RepeatDirection="Vertical"
RepeatColumns="4" Width="100%" DataSourceID="LanguagesSDS"
DataTextField="Language" DataValueField="ID">
</asp:CheckBoxList>
<asp:SqlDataSource ID="LanguagesSDS" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="select ID, [Language] from LanguagesListTable"
DataSourceMode="DataReader">
</asp:SqlDataSource>
Obviously these particular controls are not yet generated or on the page by the time my _PrefillWizard has been called, resulting in none of the CheckBoxes being pre-filled. How do I make them generate before my prefill method is called? Thanks ;)
The click event that kicks things off.
'On "Load" Button click, clears a Wizard control and Prefills it with the
' data from the clicked record based on the primary key stored in SessionState.
Protected Sub RowClick(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "Select" Then
Session.Add("ClickedPrimaryKey", GridView2.DataKeys(e.CommandArgument).Value.ToString)
'This is the main function which calls "_SetCheckBoxes" among others.
_PrefillWizard(Session.Item("ClickedPrimaryKey"))
End If
End Sub
Here's my function for populating the my CheckBoxList control, but it obviously depends on the control having already been loaded on the page.
'Parse a CSV String from the Database back into CheckBoxList Selections
Protected Sub _SetCheckBoxes(ByRef cbl As CheckBoxList, ByRef dt As DataTable, ByVal row As Integer, ByVal csv As String)
'Do something if there is a value in the cell
If Not IsDBNull(dt.Rows.Find(row)(csv)) Then
For Each item As ListItem In cbl.Items
item.Selected = False 'Reset the checkbox first
'Then, if the ID value of the checkbox corresponds to a value
' in the CSV string, then tick the checkbox.
If csv.Contains(item.Value) Then
item.Selected = True
End If
Next
End If
End Sub
Here is a potential idea, and one that we have used before in a similar situation:
Because the Page Init event is fired before the click handler, you can actually examine Request.Form("__EventTarget") and, if it is your row click, add the new CheckBoxList to the appropriate container (page, tab, etc).
If you are adding multiple controls, you will have to be sure that you track the added items somewhere in the page so that they can be automatically re-created each time Page Init is fired.
You guys will probably get a kick out of this, but the answer was so obvious that I didn't even catch it all this time. Of course I was preoccupied with about 10 other functions too >.<
Here's the answer. You'll notice that in my _SetCheckBoxes method, I first checked to ensure that a value existed for the particular csv string, but also notice, that I failed to actually SET it to the corresponding value string afterward. This isn't immediately apparent, but what I was actually passing in as csv was the name of the Column in my DataTable where the string actually lived.
csv = dt.Rows.Find(row)(csv).ToString
That line added immediately after my IsDBNull check, fixed my problem. :)

How to check checkboxes according to textbox text !

If in textbox the default textbox value id 1,2,3,4,5,6 ...... upto 55
then the following checkboxes would be checked according to the text display in text box...
if textbox1.text =1,2,3 then in my webform checkbox1, checkbox2, checkbox3 would be checked ... on page load event...
how to do this ?
Dim splitted as String() = MyTextBox.Text.Split(",")
For Each id As String in splitted
Dim ctrl as Control = Page.FindControl("checkbox" & id)
If Not control Is Nothing Then
Dim chkbox As CheckBox = DirectCast(ctrl, CheckBox)
chkbox.Checked = True
End If
Next
I'm actually a C# programmer, so not 100% if the VB.NET syntax is correct. Another NB! is that this sample only works if the checkboxes are directly in your ASP.NET page. If they're ie. inside an ASP:Panel, then you'll have to use "MyPanel.FindControl" istead of Page.FindControl
55 checkboxes? You could have lots of if...else to check each number, but I would create a collection of checkboxes. Then parse the number in the text box check it is in range and then simply look up correct checkbox to check according using the value as an index.
Another thought: It sounds like one and only one checkbox should be set at a time? If so, you should replace them with a group of radio buttons. As well as being easier to code, it avoids duplicate checkbox checks, and signals to the user that only one can be set.

Insert record with EmptyDataTemplate in asp:ListView

I have an EmptyDataTemplate in my asp:ListView which I want to use to insert a new record.
I have Inserting working in the InsertItemTemplate... I thought I could copy the InsertItemTemplate into the EmptyDataTemplate, on clicking Insert this gives the error
Insert can only be called on an insert item. Ensure only the InsertTemplate has a button with CommandName=Insert.
How can I use the EmptyDataTemplate to Insert a row? Do I need to use the OnClick of the button to access the values within the EmptyDataTemplate and do an Insert by myself?
I'm using LinqDataSource
You might have figured it by now
but if you set the InsertItemPosition to anything other than None the EmptyData Template will not be rendered i.e it will always show the insert template
you can read more here
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.emptydatatemplate.aspx
No way if want to insert data in empty data template.
It is possible to do an insert from the EmptyDataTemplate by handcrafting the insert. I am using a listview to display a static number of rows based on a unique filtered item. I am basically listing all the static attributes of an object. In the case where a new object is filtered on that does not have any attributes associated with it, i use the EmptyDataTemplate of the listview to display a HTMLTable that contains asp.net controls to capture data. I have a command button within the table that i evaluate using the ListView_ItemCommand. If the CommandName matches that of the "Insert" button within the EmptyDataItem, I use the ListView.Controls(0).FindControl method to locate my table. I then loop through my table and do inserts on the data found within each row. I included the how to find a control within the htmltable. In my code I am actually grabbing a bunch of controls then crafting the sql and using a SQLConnection to perform the insert.
Protected Sub ListView_ItemCommand(sender As Object, e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView.ItemCommand
Select Case e.CommandName
Case "Submit"
Dim edt As HtmlTable = ListView.Controls(0).FindControl("myhtmltable")
Dim ddl As DropDownList = CType(edt.FindControl("mydropdownlist"), DropDownList)
'Perform Insert
Case "Some other commandname"
End Select
End Sub
You will need to still do error checking and databind() and refresh your listview.
Is this the best way. Maybe not... But it is possible.
~Ian

Resources