VB.NET checkboxes - asp.net

I have a aspx page which contains the following CheckBoxList.
<form id="form1" runat="server">
<asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server">
</asp:CheckBoxList>
<br />
<asp:label id="mess" runat="server"/>
</form>
Then in the .vb page I have a query in the Page_Load sub where I get all the customer names and whether or not they are a validated user (either true or false). When I loop through the dataset I want to add a ListItem for each name and if they are a validated user I want to have the checkbox checked. Here is my loop for the dataset
For i = 0 To dt.Rows.Count - 1
If CStr(dt.Rows(i).Item("isValid")) = True Then
"<asp:ListItem>" + CStr(dt.Rows(i).Item("Name")) + "</asp:ListItem>"
Else
"<asp:ListItem>" + CStr(dt.Rows(i).Item("Name")) + "</asp:ListItem>"
End If
I know the above loop isnt going to add the listItems, how do I add the checked ListItems in my loop? Any help would be appreciated. Thanks
I know there is a way to check if a box is checked such as doing
check1.Items(i).Selected
How do you check if it is not checked? Something like this?:
check1.Items(i).Selected = False

You can add items to the CheckBoxList by using CheckBoxList.Items.Add(ListItem). ListItem has a property Selected for the checked state:
For Each row As DataRow In dt.Rows
Dim name = row.Field(Of String)("Name")
Dim isValid = row.Field(Of Boolean)("isValid")
Dim item = New ListItem(name)
item.Selected = isValid
check1.Items.Add(item)
Next

I dont know VB, but in C# it would be like check1.items.add(new ListItem("val")) to add each ListItem.

Related

How to get Repeater's current ItemIndex in code behind

While Container.ItemIndex as a way to get current repeater's item index in data binding expression works perfectly fine <%# Container.ItemIndex %>, it does not work in pure code behind. Container is not declared or inaccessible.
How can I get repeater's current item index here:
<ItemTemplate>
<% If Container.ItemIndex = 2 Then %>
TRUE/some longer HTML here/
<% Else %>
false/some longer HTML here/
<% End If %>
</ItemTemplate>
EDIT
For cases with not much HTML code this will work, but I am looking for Code Render Block solution as per example above.
<%#: If(Container.ItemIndex = 2, "TRUE", "false") %>
Ok, just drop in a button and pick up the repeter row.
So, say we have this repeater markup:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:290px;float:left;padding:10px">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' />
<br />
City: <asp:TextBox ID="City" runat="server" Text ='<%# Eval("City") %>' />
<br />
Province: <asp:TextBox ID="Province" runat="server" Text ='<%# Eval("Province") %>'/>
<br />
Active: <asp:CheckBox ID="chkActive" runat="server" Checked = '<%# Eval("Active") %>'/>
<br />
<asp:Button ID="cmdRowC" runat="server" Text="Row Click" OnClick="cmdRowC_Click"/>
</div>
</div>
<div style="clear:both;height:5px"></div>
</ItemTemplate>
</asp:Repeater>
and our code behind to fill this repeater:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using cmdSQL As New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Repeater1.DataSource = cmdSQL.ExecuteReader
Repeater1.DataBind()
End Using
End Sub
And we now have this:
So now the button code. Note how I just dropped in a standard button.
But, we now can't double click on the button to automatic wire up and create a event.
BUT YOU CAN do this to create a event:
In the button code markup, type in OnClick=
WHEN YOU HIT "=", then intel-sense will pop up a dialog for you to create a button click event like this:
So, now click on create new event. It "seems" like nothing occured, but if we flip to code behind you find the click event stub.
So, now in our click event code we can easy pick up the current repeater row, the values and yes even the index.
The code works like this:
Protected Sub cmdRowC_Click(sender As Object, e As EventArgs)
Dim cBtn As Button = sender
Dim rRow As RepeaterItem = cBtn.Parent
Debug.Print("Row clicked = " & rRow.ItemIndex)
Debug.Print("First Name = " & DirectCast(rRow.FindControl("txtFirst"), TextBox).Text)
Debug.Print("Last Name = " & DirectCast(rRow.FindControl("txtLast"), TextBox).Text)
Debug.Print("Hotel Name = " & DirectCast(rRow.FindControl("txtHotelName"), TextBox).Text)
End Sub
output:
Row clicked = 1
First Name = Darcy
Last Name = Caroll
Hotel Name = Athabasca Hotel
So, just drop in a plane jane button. When you click on it the event stub runs, and as you can see, we pick up the "Repeater row item".
From that row, we can get the row index, and of course pluck out any other control value from that row using find control.
eg:
Dim txtHotel as TextBox = rRow.FindControl("txtHotel")
debug.print ("Hotel name = " & txtHotel.Text)
So, once you have the repeater row, you don't need some container.ItemIndex expression, since the row item lets you get the given index row with:
rRow.ItemIndex
So, ItemIndex is available, and is avilable regardless if you have or include or use the conttin.ItemIndex in the markup.
There is VERY LITTLE need to mess around with that code in the markup.
Note how VERY clean and simple the above is. I suggest you MAKE HUGE efforts to avoid dumping vb code inside of the markup like you are doing. If you even want to convert to c#, or even just maintain that code? Put that code in the code behind area - not in the markup.
As above shows, for repeating data etc., you can use a Repeater, or even often I use a listview - as it allows a repeating layout to be created automatic for you, and without having to write looping code.
******************** EDIT ***************************
Ok, now that we have this working, say we wanted to put in a message in the repeater that
This hotel is Active
or
This hotel is NOT active!
Ok, so in our markup, we could drop in a label like this:
And now from the repeater property sheet, double click here to create the item data bound event:
It is now a simple matter to put in our code logic for each row like this:
Protected Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Dim rRow As RepeaterItem = e.Item
Dim ckbox As CheckBox = rRow.FindControl("chkActive")
Dim MyLabel As Label = rRow.FindControl("Label1")
If ckbox.Checked Then
MyLabel.Text = "This Hotel is Active!!!"
Else
MyLabel.Text = "Not active!"
End If
End Sub
And output is now this:
So, once again, to conditional format the repeater, add color to active hotel, or whatever? Use the item bound event.
Say i wanted add to above that the HotelName is to be color blue when active, then we could do this:
Protected Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Dim rRow As RepeaterItem = e.Item
Dim ckbox As CheckBox = rRow.FindControl("chkActive")
Dim MyLabel As Label = rRow.FindControl("Label1")
If ckbox.Checked Then
MyLabel.Text = "This Hotel is Active!!!"
Else
MyLabel.Text = "Not active!"
End If
Dim txtHotel As TextBox = rRow.FindControl("txtHotelName")
If ckbox.Checked Then
txtHotel.BackColor = Drawing.Color.AliceBlue
End If
End Sub
Again, nice easy clean code - no mess markup. We seperate the code logic from the markup.
Output now is this:
Again, note how we did not even write ANY looping code here!!!!
So you want to leverage the built in options for the repeater, and for a GridView, listView, and a repeater?
Use the row data bind event - it lets you format, even do math, or whatever you want for EACH row of the repeating controls. And as you can see, its plain jane easy to write code as a bonus.

How to make auto select item in checkbox list with condition in vb.net

I have a checkbox list which the item is yes and no. For example, If textbox1 <= 90 then 1stitem in checkboxlist which is "Yes" will auto select. If textbox1 >90 then 2nditem in checkboxlist which is "No" will auto select. How to write this code in vb?
Thanks!
You need to handle OnTextChanged event of TextBox control. Following is a sample aspx file code
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="Yes" Text="Yes"></asp:ListItem>
<asp:ListItem Value="No" Text="No"></asp:ListItem>
</asp:CheckBoxList>
Back end code
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
Dim valueString As String = TextBox1.Text
Dim value As Integer
If Integer.TryParse(valueString, value) Then
If value <= 90 Then
CheckBoxList1.Items.FindByValue("Yes").Selected = True
CheckBoxList1.Items.FindByValue("No").Selected = False
Else
CheckBoxList1.Items.FindByValue("Yes").Selected = False
CheckBoxList1.Items.FindByValue("No").Selected = True
End If
End If
End Sub
One way to do this is in the textbox leave event, check the numeric value of the text and then check the appropriate value in the checkboxlist. You can use IsNumeric to make sure the value in the textbox is a number.

check if certain textboxes are empty

ok, I needed to check if only 4 out of 15 textboxes were empty, but with no luck. I tried:
if txtbox1.text = "" then
lblerror1.visible=true
exitsub
else
bla bla
end if
But that left error text and didn't see the user entering the text in the textbox, so I looked and found string.isnullorwhitespace(string.value)...
well, that didn't tell me how to use it so I searched more and found this:
if string.isnullorwhitespace(textbox.text) then..
well that was it and here is the outcome. now if I could only get a for-next or do -while to only chaeck the 4 text fileds I need to check and not all textboxes.
ASPX page code:
<asp:Label ID="lblerror" runat="server" Text="Page error" Visible="false" forecolor="red"/><br />
<asp:TextBox ID="txtName" runat="server" Width="100px" /><asp:Label ID="nameblankerror" runat='server' Text="cannot be blank" ForeColor="Red" Visible="false" /><br />
<asp:TextBox ID="txtcompname" runat="server" Width="100px" /><asp:Label ID="compblankerror" runat='server' Text="cannot be blank" ForeColor="Red" Visible="false" /><br />
<asp:Button ID="btnSubmit" runat="server" Text="submit" /><br />
<asp:Label ID="lbl1" runat="server" Visible="true" Text="TextBox 1: " /><asp:label ID="lblname" runat="server" /><br />
<asp:Label ID="lbl2" runat="server" Visible="true" Text="TextBox 2: " /><asp:label ID="lblCompName" runat="server" />
and for the backend code:
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'test to see if certain the fields are blank
Dim str1 As String = txtName.Text
Dim str2 As String = txtcompname.Text
Dim CatchMe As Integer = 0
If String.IsNullOrWhiteSpace(txtName.Text) Then
nameblankerror.Visible = True
CatchMe += 1
Else
nameblankerror.Visible = False
lblname.text = str1.Trim()
CatchMe += 0
End If
If String.IsNullOrWhiteSpace(txtcompname.Text) Then
compblankerror.Visible = True
CatchMe += 1
Else
compblankerror.Visible = False
lblCompName.Text = str2.Trim()
CatchMe += 0
End If
If CatchMe = 0 Then
'do something like process SQL Command
lblerror.Visible = False
Exit Sub
ElseIf CatchMe <> 0 Then
'return to page and process nothing
lblerror.Visible = True
Exit Sub
End If
End Sub
so that is it. a simple, easy to follow check for certain textboxes out of a bunch.
Like I stated above if I could figure out how to check only certain textboxes and not all textboxes, that and make the code shorter would be great. I put in a catchme so that if one box was filled in it wouldn't show the user that they need to fill that one also (in Error), but would catch the other empty textboxes.
to make it clear, if I have 15 textboxes, but only care that 4 of them are not empty, this is what I do for the check. I don't do this for every textbox as it is not needed
Add unique CssClass to all 4 TestBox.
Find the parent control which holds all 4 TextBox.
And then try the following code.
If you have applied validateempty as CssClass for TextBox and if Ctrl1 is the parent control which holds the textboxes then.
For Each ctrl as Control In Ctrl1.Controls
Dim txt as TextBox = TryCast(ctrl, TextBox)
If txt IsNot Nothing And txt.CssClass = "validateempty" And txt.Text.Trim() = "" Then
'Your choice of code hear.
End If
Next
Using JQuery you can find an element by its cssclass name.
First add the JQuery reference to your page You can find it hear.
Second add the following function to OnClientClick attribute of the submit button.
function validate(){
//Since you have added cssclass for the textboxes as "validateempty" then
var ret = true;
$.find(".validateempty").each(function(){
if(ret){
if($(this).val().trim() == ""){
alert("Enter the value.");
$(this).focus();
ret = false;
}
}
});
return ret;
}
$.find() will find all elements with the provided filter parameter. In this case css class. If there are more than one value is returned as there are 4 text boxes, then loop through the result and check individual found element which can be found in $(this) element. If you specify return directly inside the $.find(), then it will return from the loop not from function.
You can maintain an array of Id's you want to validate.
String[] txtboxToValidate = { "txtb1", "txtb2", "txtb4", "txtb8" };
foreach (Control c in Page.Controls)
{
if (c is TextBox)
{
int pos = Array.IndexOf(txtboxToValidate, c.ID);
TextBox txtBox = (TextBox)c;
if (pos > -1)
{
if (String.IsNullOrEmpty(txtBox.Text))
{
//Write your logic how you want to throw your error.
}
}
}
}
It's in c# but logic remains same. You can convert it to VB using online code converters etc.

Gridview in user control page (ascx) is null

I have a page from where a user can search for items and so on. I use a .ascx page to display the result in a grdview.
The aspx page only has a seacrh box and a button and on button click I want to pass the value from inside the textbox to the ascx page and have the gridview populate with the result. But after debugging I found that the gridview is set to null after the button click. All other values are there and the result comes back from the database.
Can some one please help. I have been looking for a solution for last few hours and have treid a few diffeerent things but still not getting anywhere.
thanks in advance
EDIT
Here is my code
This is the aspx page.
<%# Register Src="Search.ascx" TagName="Search" TagPrefix="uc1" %>
<form id="form1" runat="server">
<div class="content">
<div style="padding:5px;">
<b>Search</b>: <asp:TextBox runat="server" ID="txtSearch" />
<asp:RequiredFieldValidator ErrorMessage="*" ValidationGroup="SearchGroup" ControlToValidate="txtSearch" ID="RequiredFieldValidator1"
runat="server" />
</div>
<div style="padding:5px;">
<asp:Button Text="Search" runat="server" ValidationGroup="SearchGroup" OnClick="btnSearch_Click" ID="btnSearch" />
</div>
</div>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div class="Results">
<uc1:Search ID="UserControl1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
In the ASCX page I have the following
The code behind
Dim test As Object = txtSearch.Text
Dim StockList As cls_Stock_Col = MyLOTSDB.LoadStock_Col()
Try
Dim dt As DataTable = New DataTable()
Dim dcol As New DataColumn("TradeName", GetType(System.String))
dt.Columns.Add(dcol)
'Create an ID column for adding to the Datatable
dcol = New DataColumn("PackSize", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("PLU", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("SOH", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("RetailAsCurrency", GetType(System.String))
dt.Columns.Add(dcol)
For Each col As DataColumn In dt.Columns
'Declare the bound field and allocate memory for the bound field.
Dim bfield As New BoundField()
'Initalize the DataField value.
bfield.DataField = col.ColumnName
'Initialize the HeaderText field value.
Dim DisplayName As String = ""
Dim DataFormat As String = ""
Dim FieldType As Type = col.GetType()
Dim StringLength As Int32
GetFieldDetails(TheType, col.ColumnName, DisplayName, DataFormat, FieldType, StringLength)
bfield.HeaderText = DisplayName
If (DataFormat = "$0.00") Then
bfield.DataFormatString = "{0:C2}"
End If
bfield.SortExpression = "col.ColumnName"
'Add the newly created bound field to the GridView.
GridView1.Columns.Add(bfield)
Next
GridView1.DataSource = StockList
GridView1.DataBind()
Catch ex As Exception
End Try
I can debug and the error is thrown when I try to add the column to the gridview,
Thanks again
The aspx page only has a seacrh box and a button and on
button click I want to pass the value from inside the textbox to the ascx page
You can do this by specifying a public property on your ascx control which you can access on calling page.
Inside your ascx code behind
private string searchText ;
Public string SetSearchText
{
get { return searchText; }
set { return searchText; }
}
In your calling page on button click, just set the property of the ascx control
Inside your main page on button click
YourAscxControl.SetSearchText= yourTextBox.Text.Trim();
User Dynamic Content Place Holder .
Refer to following links they might help:-
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
http://www.codeproject.com/Articles/18080/Solve-Dynamic-Control-Problem-With-PostBack

checkbox.checked is not working in a listview

I've got an aspx using master pages and .net 4. I've using the same code on 4 different forms. I've copied and pasted it from the other forms that are working. Here is the code.
The listview is named lvMisc_Attachment, here is the Checkbox code
<asp:CheckBox ID="chkChecked" runat="server" Checked='<%#eval("Checked") %>' />
and here is the code behind that is happening when someone clicks a linkbutton, the linkbutton calls teh MiscAttachment_ItemsChecked function.
Private Function MiscAttachment_ItemsChecked() As String
Dim mString As String = String.Empty
For Each lv In Me.lvMisc_Attachment.Items
If CType(lv.FindControl("chkChecked"), CheckBox).Checked = True Then
If mString.Length = 0 Then
mString = CType(lv.FindControl("hfMisc_AttachmentID"), HiddenField).Value
Else
mString = mString & "," & CType(lv.FindControl("hfMisc_AttachmentID"), HiddenField).Value
End If
End If
Next
Return mString
End Function
The checkbox does not show up as being checked when it is. It is getting checked after the page renders.
Add AutoPostback="true" to your checkbox in order to post contol whan he changes
<asp:CheckBox ID="chkChecked" runat="server" Checked='<%#eval("Checked") %>' AutoPostback="true"/>
I found the problem. I forgot to do a if page.ispost=true on the page_Load.. the listview was getting repopulated so the checkbox wasn't checked due to the reload.

Resources