I am trying to stop the user to enter a numerical value in the search criteria text box when the Dropdown value is MBID The code works I only need help on how to resolve the validation issue
C# Code
protected bool searchData()
{
string val = DropDownList1.SelectedItem.Value;
switch (val)
{
case "MBID":
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT count(*)
from Patient where MBID = #SearchCriteria ", con))
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
int userCount = (Int32)cmd.ExecuteScalar();
da.Fill(dt);
}
}
}
}
The Search button call the code below
protected void btnSearch_Click(object sender, EventArgs e)
{
if (FormValidation()) if (searchData())
{
BindGrid();
inputUpdateFornData();
}
}
HTML Code
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="MBID">MBID</asp:ListItem>
<asp:ListItem Value="HPNumber">HP Number</asp:ListItem>
<asp:ListItem Value="NHSNumber">NHS Number</asp:ListItem>
I cannot used the code below because numerical value can be entered for the other option of the dropdown
<asp:TextBox ID="txtSearchCriteria" runat="server />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtSearchCriteria" Type="Integer"
Operator="DataTypeCheck" ErrorMessage="Value must be an integer!" />
This is how to do it:
try
{
int d = int.Parse(txtSearchCriteria.Text);
//if works str is a number
}
catch (Exception e)
{
Console.WriteLine("It isn't a number!");
}
Add ClientValidationFunction="validateFunction" in your CompareValidator.
And write validation function as follows-
function validateFunction(s,args){
if (yourdropdown.value == "MBID")
{
// Your code
}
}
If you want server validation , add OnServerValidate attribute and handler function on server side.
hello please try below code for javascript validation
below is javascript code
<script>
function validateSearch()
{
var dropdown = document.getElementById("<%= ddlSearch.ClientID %>");
var txtSearch = document.getElementById("<%= txtSearch.ClientID %>");
if (dropdown.value == "MBID")
{
var reg = /^\d+$/;
if (!reg.test(txtSearch.value)) {
alert("Please enter proper value");
txtSearch.focus();
return false;
}
}
}
</script>
and below is aspx code of dropdown and textbox.
<asp:DropDownList runat="server" ID="ddlSearch">
<asp:ListItem Text="Select" Value="-1"></asp:ListItem>
<asp:ListItem Text="MBID" Value="MBID"></asp:ListItem>
<asp:ListItem Text="Name" Value="Name"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:Button runat="server" ID="btnSearch" Text="Search" OnClientClick="return validateSearch();" />
Related
I'm struggling a lot and I hope someone can help me please.
I have a 4 dropdownlists, a search button and a normal gridview with a basic SQLdataConnection.
The SQLdataConnection is a stored procedure that retrieves 3 tables based on 4 parameters. These 3 tables are then joined together into the gridview.
BUT
One of the dropdownlists has the options of Total, Fast and Slow. So based on which option the user chooses the respective table should be loaded into the gridview when the search button is pressed. (So if total is chosen, the total table should be loaded into the gridview)
I don't know if the SQLdataConnection should be changed with each option to show only the appropriate table.
Below is a copy of the html of the dropdowns and gridview as well as the code behind.
<tr>
<td style="text-align: right" class="pad-right-0">
<asp:DropDownList ID="selSeconds" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selHours" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selMerchantId" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selTableType" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" OnClick="btnSearch_Click" Text="<%$Resources:Resource, btnSearch %>" />
<asp:ImageButton ID="btnExportToExcel" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" onclick="btnExportToExcel_Click" Text="Export to excel" ImageUrl="images/Excel.png" AlternateText="<%$Resources:Resource, lblExportExcel %>"
CausesValidation="false" />
<asp:RequiredFieldValidator ID="rqrdMerchantId" runat="server" ErrorMessage="<%$Resources:Resource, lblRequired %>" ControlToValidate="selMerchantId" ForeColor="Red" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnMerchantId" runat="server" Value="0" />
<asp:GridView ID="gridSpeedAnalysis" runat="server" DataSourceID="gridSqlConnection">
</asp:GridView>
<asp:SqlDataSource ID="gridSqlConnection" runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null || Session["UserType"] == null)
{
Response.Redirect("Login.aspx");
}
LoadDropDowns();
}
private void LoadDropDowns()
{
System.Web.UI.WebControls.ListItem item;
selSeconds.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select Second", "0"));
int index = 1;
for (int Second = 0; Second <= 10; Second++)
{
System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(Second.ToString(), Second.ToString());
selSeconds.Items.Insert(index, li);
index++;
}
item = selSeconds.Items.FindByValue(DateTime.Now.Year.ToString());
selSeconds.SelectedIndex = selSeconds.Items.IndexOf(item);
if (Session["UserType"] != null && (Session["UserType"].ToString().ToLower() == "System Administrator".ToLower()))
{
selMerchantId.DataSource = BOL.MerchantGroup.Load();
selMerchantId.DataTextField = "Description";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = "0", Text = "Select Group" });
rqrdMerchantId.InitialValue = "0";
}
else if (Session["UserType"].ToString().ToLower() == "Head Office".ToLower())
{
BOL.MerchantGroup group = new BOL.MerchantGroup(int.Parse(hdnMerchantId.Value));
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = hdnMerchantId.Value, Text = group.Description });
}
DataTable dt = BOL.Merchant.GetDropdownByMerhcantGroupId(int.Parse(Session["MerchantGroupId"].ToString()));
selMerchantId.DataSource = dt;
selMerchantId.DataTextField = "Name";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Total"});
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Fast" });
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Slow" });
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}
I want to force the user to change the selection of the first drop down list IF he/she selected a particular value in the second drop down list.
<asp:DropDownList ID="ddlGxP" runat="server" CssClass="stdDropdownSmall" OnSelectedIndexChanged="ddlGxP_SelectedIndexChanged" AutoPostBack="true" />
<
else
{
}
The above is the first drop down list where the user should select value from "ddlGxP"
The following is the second drop down list where I need to make the check when the user make a selection, I have to check on the first drop down.
<div class="divStandard">
<asp:Label ID="Label23" runat="server" CssClass="stdLabel">nalized Method <span class="mandatory"> *</span></asp:Label>
<asp:DropDownList ID="ddlFinalizedMethod" runat="server" CssClass="stdDropdown" />
<asp:CustomValidator ID="cvFinalizedMethod" runat="server" ControlToValidate="ddlFinalizedMethod" InitialValue="0" OnServerValidate="cvFinalizedMethod_ServerValidate"
CssClass="RequiredFieldError" ErrorMessage=" ! Please select another GxP Standard" />
} else {
<asp:TextBox ID="txtFinalizedMethodDisabled" runat="server" CssClass="stdTextboxSmallDisabled" Enabled="false" />
}
</div>
i don't have enough reputation so here is my comment.
i just want to clarify the problem in basic terms.
your design view consists of two dropdownlists.
you make a selection on dropdownlist1, its selectedindexchanged is triggered performing some sort of action.
you now make a selection on dropdownlist2, its selectedindexchanged is triggered and performs some sort of manipulation on dropdownlist1, either changing its contents or selected value;
SORRY FOR THE WAIT, I MADE SOME SIMPLE ERRORS DUE TO FORGETTING SOME THINGS;
The ANSWER!!!!
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
onselectedindexchanged="ddl2_selectindexchange">
</asp:DropDownList>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> str = new List<string>();
str.Add("red");
str.Add("blue");
str.Add("black");
List<string> str2 = new List<string>();
str2.Add("red");
str2.Add("blue");
str2.Add("black");
DropDownList1.DataSource = null;
DropDownList1.DataSource = str;
DropDownList1.DataBind();
DropDownList2.DataSource = null;
DropDownList2.DataSource = str2;
DropDownList2.DataBind();
}
}
protected void ddl2_selectindexchange(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
ddl = sender as DropDownList;
ListItem li = new ListItem();
li = ddl.SelectedItem;
string s = li.Text;
Label1.Text = s;
}
i am new on .net development now i am facing the problem but i do not know what the solution for this
i am creating the dropdown list and bind it with data but when i select the any data from list it does not changes the textbox with the related value but when i click on button it goes inside the code means goes on debuging from where i mark the debug cursor
here is my code behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCardCode = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=testing;Initial Catalog=testdb;Persist Security Info=True;User ID=abcd;Password=asdfg");
using (connection)
{
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName,T3.CntctCode,T3.Name FROM OCRD T1 inner join OCPR T3 on T1.CardCode=T3.CardCode where T3.CardCode=#CardCode ", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selectedCardCode);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.DropDownList1.SelectedItem.Value = selectedCardCode;
}
connection.Close();
}
}
and here is my method cardcode
protected void LoadOptionsCardCodeTable()
{
DataTable CardCode = new DataTable();
string id, name, newName;
SqlConnection connection = new SqlConnection("Data Source=abc;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=asdf;Password=asdfgh");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName from ocrd T1 ", connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = name + " ---- " + id;
DropDownList1.Items.Add(new ListItem(newName, id));
}
}
}
}
here is my design code
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
</form>
Kindly help your help will be higly appreciatable
Set AutoPostBack property to true for your dropdownlist.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
By default, asp.net server controls like dropdownlist, textbox have their respective events as cached which means it registers the event but does not fire untill an actual postback happens. In you case when you are clicking the button a postback is happening and the cached event of your dropdwonlist is also getting executed.
To force postback from your dropdown you will have to set the PostBack property to true.
You have to set AutoPostBack="true" in order to trigger the event:
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Notes:
A postback is initiated by the browser, and reloads the whole page, according to an event.if any changes(here onselectedindexchanged) we made in the control result in a postback then that are called AutoPostBack.All controls except, Buttons, Hyperlinks and LinkButtons have a default AutoPostBack property of false, we have an option to make them true if needed.
Set AutoPostBack="true" Otherwise DropDownList1_SelectedIndexChanged doesn't fire.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
I have two dropdownlists in my page:
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
My code-behind to handle the dropdownlist change is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;
public partial class physicians : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
PopulatePhysician();
}
//PopulateSpecialty();
//PopulateLocation();
}
public void PopulatePhysician() {
SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
//cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Physician's Name";
Item.Value = "0";
//Item.Selected = True
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateSpecialty() {
SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Specialty";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateLocation() {
SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Location";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
switch(ddlMain.SelectedIndex) {
case 0:
PopulatePhysician();
break;
case 1:
PopulateLocation();
break;
case 2:
PopulateSpecialty();
break;
}
}
}
The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.
How can I achieve it?
UPDATE:
<asp:ScriptManager ID="ScriptManager"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
Use AJAX. Place both dropdown controls in UpdatePanel and just after the opening Form tag in the page add a ScriptManager (if not already there)
If this is the case, Ajax method should resolve your problem.
Since you are quite new to Ajax, I would describe a bit more details.
There must be only one ScriptManager in the same page.
( If you are using Master page, add to master page and no need to add anymore in nested content page )
Add UpdatePanel and add your controls to ContentTemplate of UpdatePanel.
Add AutoPostBack="True" to your main dropdownlist.
Add SelectedIndexChanged event by double clicking on main dropdownlist.
In SelectedIndexChanged event of main dropdownlist, clear the ddlDrillDown items by adding ddlDrillDown.Items.Clear() method and rebind the data whatever you need based on the value of main dropdown list.
You can use ajax for this goal.
Create asmx-service or webApi controller which return list of items. Call this on change and render it.
As suggested you can use an UpdatePanel. And please do not use ClientIDMode="Static" unless you really, really need to.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ID="ddlMain" runat="server">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<asp:DropDownList ID="ddlDrillDown" name="searchPhys" runat="server">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
Now the problem with UpdatePanel is that it does not refresh the page, but does reload the DOM. So any changes made with jQuery are lost. That is why you lose the DropKick CSS.
You need to trigger $("#ID").dropkick( again. And for that you can use PageRequestManager.
<script type="text/javascript">
$(document).ready(function () {
TriggerDropkick();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
TriggerDropkick();
});
function TriggerDropkick() {
$("#<%= ddlMain.ClientID %>, #<%= ddlDrillDown.ClientID %>").dropkick({
mobile: true
});
}
</script>
Also suggested is using a service to get the values for the DropDownList. This is possible but since this is webforms you would need to disable some validation in order to prevent the Invalid postback or callback argument exception.
Another way you can use is Asp.Net [Webmethod] Attribute.
Create a method with [Webmethod] attribute on your server-side code.
On the front end, use window.PageMethods.(your method name) to invoke the server call.
I used the dependency dropdownlist method. How?:
The contents of DropDownList1_SelectedIndexChanged put in a Sub
For example:
Sub Drop1()
YOURCOD
End Sub
in DropDownList1_SelectedIndexChanged call Drop1()
Create the same for DropDownList2_SelectedIndexChanged (Drop2())
Now in DropDownList1_SelectedIndexChanged call Drop1 and Drop2.
That's it.
I am creating a survey form wherein I want the responses selected by the survey taker using the radiobuttonlist to be stored in the database. Since I have used a repeator to do this I am unable to get that data
Repeator code:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table style="border:1px solid #A55129; background-color:aqua">
<tr>
<td style="width:200px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" >
<asp:ListItem Text="1" Value="Bad"></asp:ListItem>
<asp:ListItem Text="2" Value="Fair"></asp:ListItem>
<asp:ListItem Text="3" Value="Very Good"></asp:ListItem>
<asp:ListItem Text="4" Value="Good"></asp:ListItem>
<asp:ListItem Text="5" Value="Excellent"></asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
code behind file:
protected void Button1_Click(object sender, EventArgs e)
{
int answer;
try
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
RadioButtonList rb = (RadioButtonList)item.FindControl("RadioButtonList1");
answer = Convert.ToInt32((rb.SelectedItem != null) ? rb.SelectedItem.Value.ToString() : "");
SaveResponse(answer);
}
}
}
catch (Exception)
{
}
}
private void SaveResponse(int answer)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SurveyUserdataConnectionString2"].ConnectionString);
conn.Open();
string registerquery = "Insert into surveyresponses (ANSWER) values (#ans)";
SqlCommand comm = new SqlCommand(registerquery, conn);
comm.Parameters.AddWithValue("#ans", answer);
conn.Close();
}
You need to do a comm.ExecuteQuery() for the actual insert to happen. That is why you are not seeing the data inserted.
In fact here is a cleaner way of doing the same thing so that all objects are disposed asap.
string registerquery = "Insert into surveyresponses (ANSWER) values (#ans)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SurveyUserdataConnectionString2"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand(registerquery, conn))
{
comm.Parameters.AddWithValue("#ans", answer);
comm.ExecuteNonQuery();
}
}