If statement for drop down list - asp.net

So I have two drop down lists in my code where the data is retrieved from a SQL table.
I can't figure out an IF statement to show an error message if both of these two drop down lists have not been selected. I have added a list item in to tell the user to select a date/time.
I tried an if statement but this would not work.
If Statement:
If DropDownList2.SelectedValue And DropDownList3.SelectedValue = Nothing Then
warninginfo.Visible = True
Else
Response.Redirect("ConfirmationBooking.aspx")
End If
Code:
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource2" DataTextField="Time" DataValueField="Time" AppendDataBoundItems="True" width="162px" Height="31px">
<asp:ListItem>-- Please Select a Time --</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" CssClass="auto-style2" DataSourceID="SqlDataSource1" DataTextField="Date" DataValueField="Date" AppendDataBoundItems="True" Width="162px" Height="30px">
<asp:ListItem>-- Please Select a Date --</asp:ListItem>
</asp:DropDownList>

Your if statement is wrong. It should be (changed the AND to Or)
If DropDownList2.SelectedValue Is Nothing Or DropDownList3.SelectedValue Is Nothing Then
Another option is to make those two fields required using a RequiredFieldValidator.
<asp:RequiredFieldValidator id="reqFavoriteColor" Text="(Required)"
InitialValue="none" ControlToValidate="DropDownList2" Runat="server"
/>

Related

How to check for duplicate entries in a gridview and prevent them

I am relatively new to programming and I am having trouble figuring out how to detect and prevent a user from entering in duplicate values into a gridview I have containing multiple controls. Currently I am using a foreach loop to loop through the controls that contain the values that cannot be duplicates and it works for the most part, however when I edit the first record in a table and try to "update" the record, even if I haven't changed any values, I receive a null reference exception and I don't know why. I have attached any pertinent code below and would appreciate any and all help to come to a solution.
Please excuse the long post, I am trying to be as thorough as possible without adding irrelevant information.
To start I have a grid view with a series of controls in it allowing a user to enter information into our database. The gridview and the relevant controls can be seen below.
<asp:GridView ID="GridView2" runat="server"
EmptyDataText="No Miscellaneous" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" DataKeyNames="RecID"
ShowFooter="True" DataSourceID="SqlDataSource7" Width="95%"
OnRowDataBound="OnRowDataBound" >
<EmptyDataTemplate>
<asp:DropDownList ID="ddlMiscEquipmentNew" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID"
DataTextField="EquipmentPart" AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px" style="margin-left: 70px;" >
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscNew" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description"
AppendDataBoundItems="true" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscNew_SelectedIndexChanged"
OnDataBound="ddlMiscNew_DataBinding">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtMiscQuantityNew" runat="server" Width="95px" Style="margin-left: 68px;" AutoPostBack="True" OnTextChanged="txtMiscQuantityNew_TextChanged" />
<asp:TextBox ID="txtMiscCostNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
<asp:TextBox ID="txtMiscRequestedNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
<asp:TextBox ID="txtMiscTaxNew" runat="server" Width="95px" Text="0" />
<asp:Button ID="InsertDetail" runat="server" CommandName="InsertDetail" Height="25px" Text="Add Detail" Width="85px" UseSubmitBehavior="True" />
</EmptyDataTemplate>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowEditButton="True" FooterText="Add -->" ShowDeleteButton="true" HeaderStyle-Width="70px" />
<asp:BoundField DataField="RecID" HeaderText="RecID" SortExpression="RecID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="Miscellaneous" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="lblMiscEquipmentAdd" Text='<%# Bind("EquipmentType") %>' runat="server" Width="220px" />
<asp:Label ID="lblMiscDescriptionAdd" Text='<%# Bind("MiscDescription") %>' runat="server" Width="220px" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlMiscEquipmentEdit" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart" SelectedValue='<%# Eval("EquipmentID") %>'
AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscEdit" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" SelectedValue='<%# Eval("MiscType") %>' AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscEdit_SelectedIndexChanged">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMiscEquipmentInsert" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart"
AppendDataBoundItems="True" Width="220px" Height="20px" style="margin-left: 29px;">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscInsert" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscInsert_SelectedIndexChanged">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
There are more controls in the gridview but these are where the problem lies. As you can see there are a number of drop down lists and textboxes, the controls in question are the drop down list "ddlMiscEdit" in the edit item template and the label "lblMiscDescriptionAdd". When the user makes a selection in the aforementioned ddl and proceeds to hit the insert detail button at the end of each row it adds the values to the gridview, and in turn they are added to my database through a row command event. This works as intended, the problem I run into is when a user trys to edit the first row of the gridview and changes the value for ddlMiscEdit, it triggers a null reference exception for the label lblMiscDescriptionAdd.
In order to detect duplicates I have a For Each loop in the selectedIndexChanged event for the ddlMiscEdit drop down as shown below.
For Each row In GridView2.Rows
Dim miscdescription As Label = (CType(row.FindControl("lblMiscDescriptionAdd"), Label))
If miscdescription.Text = ddlMiscEdit.SelectedItem.Text Then
lblErrorMisc.Text = "Miscellaneous items can only be claimed once"
Return
Else
lblErrorMisc.Text = ""
Return
End If
Next
I am thinking this exception has to do with the fact that when the user clicks edit it activates the drop down list and hides the label, thus when it comes to the loop "lblMiscDescriptionAdd" doesn't exist in that specific context.
I have also tried putting the foreach loop in the row command event for the gridview in the "Update" commandName section, which leads to the same issue but in a different place. When this loop is in the Update section mentioned above, instead of receiving this exception on the first record of the gridview I receive it in the second/third/fourth record, basically everything except the first record.
I use that same foreach loop in the InsertDetail command and it works as intended preventing duplicate values from being entered into the gridview, the exception only appears when I am trying to edit a given row depending on where I put the loop.
I apologize for the long post but I don't really know how to simplify my issue beyond what I have done here. I am pretty new to programming so I don't know if I could go about doing this in a better/more efficient manner, but any help/critiques would be greatly appreciated as I am at a loss as to how to fix this problem. Thank you in advance for any effort on your part for helping me solve this.
To make a long story short?
Don't try and process the GV.What happens if other users are adding data. You may well not have re-loaded the grid with updated data.
In your save code for the one record, simple hit/pull/query the main database and check for the record. That way you not messing around all day trying to process and pull values out of the GV.
Always try to think in terms of data management, not trying to use the actual GV as some kind of database - it only for display, and selecting the data to edit, but to check for duplicates, then simple query the database for that information and check if such records already exist.
For example, I have a simple GV with some hotels. (that working example you can try here: http://www.kallal.ca/Website11/WebForm2 ).
So, I have a add button to allow adding of a new reocrd. And I also have a "save" button. It would be in that save button that I simple add code to check say if the hotel name already exists in the database, and not allow that addition.
And what happens with edits? If a user edits existing, and again changes a name to some existing value, then again you have to deal with code to test/check that case.
So, be it adding, or editing, you need to check for that duplicate.
The code thus becomes rather simple. My save button code thus with code to check for the hotel already existing could/would look/work like this:
Protected Sub cmdSave_ServerClick(sender As Object, e As EventArgs)
' check for dupliate hotel name when saving or adding new reocrd.
Dim intPK As Integer = ViewState("PK")
Dim strSQL As String =
"SELECT HotelName FROM tblHotelsA
WHERE HotelName = #HotelName AND ID <> #ID"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#HotelName", SqlDbType.NVarChar).Value = txtHotel.Text
cmdSQL.Parameters.Add("#ID", SqlDbType.NVarChar).Value = intPK
Dim rstDataCheck As DataTable = MyrstP(cmdSQL)
If rstDataCheck.Rows.Count > 0 Then
' we have a duplicate hotel, don't allow adding!
' code here to inform user that this is a duplicate
' hotel and you can't add it.
Me.MyCustomMessage.InnerText = "Can't add this hotel - duplicate"
Exit Sub
End If
' code here to save the edit back to database
strSQL = "SELECT * FROM tblHotelsA WHERE ID = " & intPK
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL2 = New SqlCommand(strSQL, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmdSQL2)
Dim daU As New SqlCommandBuilder(da)
Dim rstData As New DataTable
rstData.Load(cmdSQL2.ExecuteReader)
With rstData.Rows(0)
.Item("HotelName") = txtHotel.Text
.Item("FirstName") = tFN.Text
.Item("LastName") = tLN.Text
.Item("City") = tCity.Text
.Item("Province") = tProvince.Text
.Item("Description") = txtNotes.Text
.Item("Active") = chkActive.Checked
.Item("Balcony") = chkBalcony.Checked
.Item("Smoking") = chkSmoking.Checked
End With
da.Update(rstData)
End Using
End Using
LoadGrid() ' refrsh grid to show any new edits
ShowGrid(True) ' hide edit area, show grid
End Sub
So, in action, then the above will look like this.
We will edit the record and try to create a duplicate.

Using Conditional Statement in ASP.NET Control Attribute

I have a DropDownList on my page and I would like the DataTextField value to be based on a condition (language). I'm using Model Binding and this DropDown is nested in a bound FormView.
This is what I'm trying to do:
<asp:DropDownList ID="DropDownList1" ItemType="BLL.HelperClasses.ItemForList"
DataValueField="id" DataTextField="<%#: (this.IsEnglish) ? "en" : "fr" %>" SelectMethod="DropDownList1_GetData"
SelectedValue="<%#: Item.Claim.CurrencyID %>" runat="server"></asp:DropDownList>
.NET is complaining that my DataTextField "server tag is not well formed". IsEnglish is a boolean property in my base page.
Anyone know how to do this without using the code-behind?
I think you have to have "Eval" inserted so for it to actually compare them don't you?
<asp:label id="Label1" runat="server" text="<%# Eval("StReply") == true ? "yes" : "no" %>" xmlns:asp="#unknown">
</asp:label>
Code was used from http://www.codeproject.com/Questions/653888/using-If-statement-in-Bind-Eval
Problem was with the surrounding double-quotes. Changed them to single-quotes and everything works perfectly.
Final solution:
<asp:DropDownList ID="DropDownList1" ItemType="BLL.HelperClasses.ItemForList"
DataValueField="id" DataTextField='<%#: (this.IsEnglish) ? "en" : "fr" %>' SelectMethod="DropDownList1_GetData"
SelectedValue="<%#: Item.Claim.CurrencyID %>" runat="server"></asp:DropDownList>

'ddpJobType' has a SelectedValue which is invalid because it does not exist in the list of items

im trying to bind the data from database to dropdownlist and i want to set the default value as "select". but i got this error.
My Code is:
<asp:DropDownList ID="ddpJobType" runat="server" Width="226px" Height="26px"
onselectedindexchanged="ddpJobType_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="0" Text="--Please Select Type--"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ErrorMessage="Please Select JobType " Font-Size="Small"
ForeColor="Red" ControlToValidate="ddpJobType"
ValidationGroup="VGPJobPost"></asp:RequiredFieldValidator>
If you are banding data using DataSource, then your default item will not be available after the call of DataBind function. You need to add it manually after calling databind something like below
dropDownList.DataSource= yourdataSource;
dropDownList.DataBind();
dropDownList.Items.Insert(0, new ListItem("--Please Select Type--", "0"));
Another option is in the designer you need to specifiy
AppendDataBoundItems=true
This will make sure your designtime list items are present after databind

Update on GridView combobox not updating

I am trying to bind the DropDownList(DDL) with my entity datasource. The GridView(GV) is bound to a different EntityDataSource than the DDL. The GV's EntityDataSource has a navigation property 'Bag' for the relationship. In edit mode I can pick a different item, but it does not update the database for that record. I did use the include for the navigations in the EntityDataSource. I am sure the wiring is not correct. I have tried searching with no luck so far. Thanks for the help.
<asp:TemplateField HeaderText="Bag">
<ItemTemplate >
<asp:Label ID="lbEditBag" Text='<%#Eval("Bag.Item1") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList runat="server" ID="ddlBags" DataSourceID="edsBags" DataTextField="Amount" DataValueField="BagId" />
</EditItemTemplate>
</asp:TemplateField>
DonA, if you've not found your answer yet I will explain what I have done to do something similar to what your after I believe.
In a gridview I have various asp:TempleteField's, one which is like this:-
<ItemTemplate>
<asp:Label ID="lblActive" runat="server" Text='<%# Bind("Active") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<%--<asp:TextBox ID="txtboxActive" runat="server" Text='<%# Bind("Active") %>' Width="20px" TextMode="SingleLine" CssClass="textboxEdit"></asp:TextBox>--%>
<asp:DropDownList ID="activeDDL" CausesValidation="False" AutoPostBack="False" runat="server"> <asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1" Selected="True"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
which as you can see has two dropdownlist items in the EditItemTemplete (I also left in similar code to yours that I used to use to bind to a database for the DDL values but I don't use anymore so is commented out)
then alongside the ID, runat="server", DataKeyNames, etc. in
<asp:Gridview ID=""...
i have
OnRowUpdated="info_GridView_RowUpdated"
This then runs in my C# code behind an SQL function to update the database table with the setting from the DDL, like so (I have also put in a few other Gridview.Databind() to reset my other gridviews)
protected void info_GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
// The update operation was successful. Retrieve the row being edited.
int index = info_GridView.EditIndex;
GridViewRow row = info_GridView.Rows[index];
int itemID = Convert.ToInt32(row.Cells[4].Text); // Cells[4] is only one available as others are being edited!
// update Active value in the database //
comm = new SqlCommand("UPDATE Products SET Active=#active WHERE ItemID=#itemID", objConn);
comm.Parameters.AddWithValue("#active", ddlValue); // this stores DDL value in database
comm.Parameters.AddWithValue("#itemID", itemID);// Convert.ToInt32(propertyRefTextBox.Text));
objConn.Open();
comm.ExecuteNonQuery();
objConn.Close();
// force update and reset selectedIndex of other gridviews //
Category_GridView.DataBind();
editImages_GridView.DataBind();
Category_GridView.SelectedIndex = -1;
editImages_GridView.SelectedIndex = -1;
}
hope the above helps.
Trev.

How to update an ASP.NET label with SqlDataSource return value

On an ASP.NET page, I have a SqlDataSource configured with the following SELECT command:
SELECT AVG(Rating) FROM [Ratings] WHERE ([AlbumID] = #AlbumID)
How would I place that average value into a label?
You need to use FormView control to put the Label in.
Something like this:
<asp:formview id="formview1" runat="server" datasourceid="your-datasource-id">
<itemtemplate>
<asp:label id="label1" runat="server" text='<%# Eval("column-name") %>' />
</itemtemplate>
</asp:formview>
Replace your-datasource-id and column-name in the above code.
PS: you might need to alter the query to have a column-name for that one value:
SELECT AVG(Rating) AS "average" FROM [Ratings] WHERE ([AlbumID] = #AlbumID)

Resources