This example is totally what I'm looking for
https://www.aspforums.net/Threads/339115/Searchable-multiselect-DropDownList-from-Database-using-jQuery-Select2-Plugin-in-ASPNet/
And after choose all the countries needed, I will click Submit button. My problem is on how to get all the selected value from ddl1.
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".js-example-placeholder-single").select2({
placeholder: "Select",
allowClear: true
});
});
</script></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h2>
Upload Attachment
</h2>
<div>
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Attachment : " class="form-control"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" class="form-control"/>
<br /><br />
<asp:Label ID="Label1" runat="server" Text="Plase select Staff No : " class="form-control"></asp:Label>
<asp:DropDownList ID="ddl1" Width="300px" runat="server" multiple="multiple" CssClass="form-control js-example-placeholder-single" ToolTip="Select " OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload Attachment" OnClick="btnUpload_Click"/>
<br /><br />
</div>
</asp:Content>
And this is C# code behind
private void PopulateDropDownList()
{
String strConnString = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_User";
cmd.Connection = con;
try
{
con.Open();
ddl1.DataSource = cmd.ExecuteReader();
ddl1.DataTextField = "IDName";
ddl1.DataValueField = "StaffNo";
ddl1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string message = "";
string rnonow = DateTime.Now.ToString("yyyyMMdd_hhmmss");
GetUploadRno();
rnoUploaded = rno;
Label4.Text = ddl1.SelectedValue; //this is where i'm stuck on how to call the ddl1 selected value. This code just only get the 1st selected value only eg : Brazil only not the other 2 below.
//below is my trial to get the selected value but fail
//foreach (ListItem item in ddl1.Items)
//{
// if (item.Selected)
// {
// insert statement here
// }
//}
}
Please help. Thank you
You can't use DropDownList for multi-select. Use ListBox e.g.
<asp:ListBox ID="ddl" runat="server" SelectionMode="Multiple" CssClass="form-control js-example-placeholder-single" ToolTip="Select">
</asp:ListBox>
In code-behind:
foreach (ListItem item in ddl.Items)
{
if (item.Selected)
{
var text = item.Text;
var value = item.Value;
}
}
I got the answer by creating a field, and jQuery store the data into it.
$('[id*=ddl1]').on('change', function () {
$('[id*=hfSelected]').val($(this).val());
});
<asp:HiddenField ID="hfSelected" runat="server" />
Related
In .aspx page , I’ve taken Label Control in order to display question form the database,
4 radio buttons in order to display four option related to a particular question, and last but not the least, I’ve used hidden field in which I will store answer of the particular question.
And finally I’ve taken a Button Control, for which I’ve created the onclick event, on which I will perform the operation to generate score.
In .aspx.cs page, on the onclick event of the button, , I’ve fetch the controls form the aspx page using code mentioned below, and further I’ve used if statement in order to see which radio button is active and have store the corresponding value in the varialbe “selans”, using this “selans”, I will compare it with the value of hidden field in order to find whether checked radio button is the correct answer or not, it the answer is correct, i.e value in “selans” matches with the value in hidden field ( the actual answer) and the variable “count” ( initially initialized with value 0) increments accordingly, and all this code is placed in the “for loop” which will execute till the no. of controls in the GridView (you can relate it with the no. of question, as for every record GridView generates new control).
But when I run it I am getting this error :-
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Source Error:
Line 115: <asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
Line 116: <asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
Line 117: <asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
Line 118: <asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
Line 119:
Source File: e:\Way2Success\Student\Examdemo.aspx Line: 117
Here the error line number is 30 in .aspx page
Have a look at my code. Show me were I am making mistaking and what is the solution.
.aspx :-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Examdemo.aspx.cs" Inherits="Student_Examdemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
<li>Tab 5</li>
</ul>
<div id="tabs-1">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4") %>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns") %>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-2">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-3">
Tab 3 Content
</div>
<div id="tabs-4">
Tab 4 Content
</div>
<div id="tabs-5">
Tab 5 Content
</div>
</div>
<input type="button" id="btnPrevious" value="Previous" style = "display:none"/>
<input type="button" id="btnNext" value="Next" />
<asp:Button class="panelButton" runat="server" Text="Finish the exam" ClientIDMode="Static" OnClick="btn_Click" />
<br />
</div>
</form>
</body>
</html>
.aspx.cs :-
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.Data;
using System.Configuration;
public partial class Student_Examdemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions");
GridView1.DataBind();
GridView2.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions WHERE SectionId=2");
GridView2.DataBind();
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
RadioButton r1, r2, r3, r4;
HiddenField hdn;
int count = 0;
int neg = 0;
int total;
int totalf=0;
int totals=0;
int totalt;
int totalfo;
int totalfi;
string selans = "-1";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
r1 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView1.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totalf = count + neg;
}
for (int i = 0; i < GridView2.Rows.Count; i++)
{
r1 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView2.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totals = count + neg;
}
total = totalf + totals;
Session["score"] = total;
}
}
You have a typing error in your GridView2 definition.
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
should be
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4")%>' GroupName="A" />
I'm hoping someone can help me as I'm beating my head against a wall trying to figure out the problem. I have a databound CheckboxList that has the SelectedIndexChanged event wired up. AutoPostBack is equal to true and ViewStateMode and EnableViewState are set to "Enabled" and "True" respectively. I have other controls on this same page with server side events that fire just fine with no issue.
The weird thing is, the event SEEMS to be firing, as I can see the page reload when I check one of the items in the list. However, when I set a debug point on the method, the debugger never breaks into that section and none of my code is firing (I've even tried having it write out silly messages just to see if the method is even firing - it's not). Here's the markup:
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
Here's the SelectedIndexChanged event:
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all the things
}
What am I missing? I feel like it must be something obvious but for the life of me, I can't see it.
Also I should note this is in the latest version of Mono so there might be some weird quirk there that's causing the issue.
One final note, there are no errors in the console if I check the browser developer tools so I don't have any weird javascript stuff going on that's causing an issue.
Update
Since it's been asked, I'm posting the entire page markup and the requisite codebehind.
Markup:
<%# Page Language="C#" MasterPageFile="~/pages/master/main.master" Inherits="Letters.Web.UI.searchLetters" AutoEventWireup="true" %>
<asp:Content runat="server" ContentPlaceHolderID="additionalCSS">
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/letters.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/font-awesome.min.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap-multiselect.css") %>" />
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="additionalJS">
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap-multiselect.js") %>">
</script>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="mainContent">
<section id="search-header">
<div class="column">
<div class="field-set">
<asp:Label id="lblTextString" runat="server" CssClass="data-label">Search for Letters</asp:Label>
<div class="data-control">
<asp:TextBox id="txtTextString" Width="100%" runat="server" CssClass="form-control searchable" placeholder="Contains Text" data-paramname="textString" />
</div>
</div>
</div>
<div class="column-small">
<div class="field-set">
<span class="data-label"> </span>
<div class="data-control">
<button id="btnSearch" runat="server" class="search-nav-buttons" onserverclick="Search_Click">
Search
</button>
</div>
</div>
</div>
</section>
<asp:PlaceHolder id="plcSearchResults" runat="server">
<section id="search-results">
<div class="filter-options">
<table>
<tbody>
<tr class="searchresults-headerstyle">
<th scope="col" class="header">Filter Options</th>
</tr>
</tbody>
</table>
<asp:Panel id="pnlLanguage" runat="server">
<h1>Languages</h1>
<asp:HiddenField id="hdlLanguages" runat="server" />
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
</asp:Panel>
</div>
<asp:GridView id="grvResults" runat="server" CssClass="table table-striped table-bordered" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" Width="70%" GridLines="None"
OnPageIndexChanging="GridView_PageIndexChanging" >
<HeaderStyle CssClass="searchresults-headerstyle" />
<FooterStyle CssClass="searchresults-footerstyle" />
<PagerStyle CssClass="pagination-style" />
<Columns>
<asp:TemplateField HeaderText="Search Results" >
<ItemTemplate>
<div class="search-result-record">
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("LetterUrl") %>' Text='<%# Letters.Tools.WebUtils.HtmlEncode(Eval("Title").ToString()) %>' />
<span>(<%# Eval("Language") %>)</span>
<span class="keywords">Keywords: <%# Eval("Categories") %></span>
<asp:Label runat="server" CssClss="language" Visible='<%# Eval("LCID").ToString() != "en" %>'>Language: <%# Eval("Language") %></asp:Label>
<div class="search-abstract">
<%# Eval("SearchAbstract") %>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</section>
</asp:PlaceHolder>
</asp:Content>
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Letters.Domain.Objects;
using Letters.Tools;
namespace Letters.Web.UI
{
public partial class searchLetters : System.Web.UI.Page
{
#region eventhandlers
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack) {
this.BindResults ();
}
}
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grvResults.PageIndex = e.NewPageIndex;
this.BindResults ();
}
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.chkLanguages);
this.FilterResults ();
}
protected void Search_Click(object sender, EventArgs e)
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
#endregion
private void FilterResults()
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (pnlLanguage.Visible) {
parameters.Add (this.chkLanguages.Attributes ["data-paramname"].ToString (), this.GetSelectedItems (this.chkLanguages));
}
//Finally, add the search string
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
private string[] GetFilterOption(string delimitedValue)
{
string[] result = null;
if (delimitedValue.Contains (",")) {
result = delimitedValue.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
} else
result = new string[] { delimitedValue };
return result;
}
private string GetSelectedItems(CheckBoxList list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private string GetSelectedItems(ListBox list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private void PopulateFilters(List<SearchResult> results)
{
var languages = (from x in results
group x by new { x.LCID, x.Language } into counts
select new { Key = counts.Key.LCID, DisplayName = string.Format("{0} ({1})", counts.Key.Language, counts.Count()) }
).ToList();
this.chkLanguages.DataSource = languages;
this.chkLanguages.DataTextField = "DisplayName";
this.chkLanguages.DataValueField = "Key";
this.chkLanguages.DataBind ();
if (!string.IsNullOrEmpty (hdlLanguages.Value)) {
string[] languageSelect = this.GetFilterOption (hdlLanguages.Value);
foreach (ListItem item in this.chkLanguages.Items) {
if (languageSelect.Contains (item.Value))
item.Selected = true;
}
}
}
private void BindResults()
{
List<SearchResult> results = this.GetSearchResults ();
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void BindResults(Dictionary<string, object> parameters)
{
List<SearchResult> results = this.GetSearchResults(parameters);
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void RegisterEvents()
{
this.grvResults.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler (GridView_PageIndexChanging);
}
private List<SearchResult> GetSearchResults()
{
return LetterService.GetSearchResults ();
}
private List<SearchResult> GetSearchResults(Dictionary<string, object> parameters)
{
return LetterService.GetSearchResults (parameters);
}
}
}
I was never able to find the exact cause to the problem. Every other type of control was able to post back events and I could properly handle their events server-side. I ended up working around this particular issue by ripping out the CheckBoxList and replacing it with a gridview that used an item template to store the value in a hidden field and display the checkbox where I could then handle the OnCheckedChanged event (see code below). This worked brilliantly.
Markup
<asp:GridView id="grvLanguages" runat="server" ShowHeader="false" ShowFooter="false" AllowPaging="false"
AllowSorting="false" GridLines="None" AutoGenerateColumns="false" data-paramname="languages" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField id="hdlValue" runat="server" Value='<%# Eval("Key") %>' />
<asp:CheckBox id="chkDisplay" runat="server" Text='<%# Eval("DisplayName") %>' OnCheckedChanged="chkLanguage_SelectedIndexChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void chkLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.grvLanguages);
this.FilterResults ();
}
I'm guessing the problem is probably some weird, esoteric bug in the Mono framework. Like I said, I don't have a problem with ANY other controls (I tested quite a few - all of their server side events handled just fine); it was just a problem with the CheckBoxList.
I'm new to c# and I'm trying to build my skills without using any of the wizard tools (eg. login wizard) provided in .net. So far I've been successful in creating a very basic login website.
I'm trying to create a user profile page that will display all the data (first name, last name, etc) of the user logged in.
Text boxes on the page should populate on Page_Load but they are not.
here is the aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UserProfile.aspx.cs" Inherits="TimeHub2.UserProfile" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="UserProfile" runat="server">
<div class="header">
<h1>TimeHub</h1>
<ul>
<li>my cards</li>
<li>profile</li>
<li>help</li>
<li><asp:Label runat="server" ID="userloggedin"></asp:Label></li>
<li><asp:button runat="server" id="buttonLogout" text="Log Out" onClick="logOutClick" /></li>
</ul>
</div>
<div>
<label for="username">username</label>
<asp:TextBox runat="server" id="username"></asp:TextBox>
<label for="first_name">first name</label>
<asp:TextBox runat="server" ID="first_name"></asp:TextBox>
<label for="middle_intial">middle initial</label>
<asp:TextBox runat="server" ID="middle_intial"></asp:TextBox>
<label for="last_name">last name</label>
<asp:TextBox runat="server" ID="last_name"></asp:TextBox>
</div>
<div>
<label for="star">star</label>
<asp:TextBox runat="server" ID="star"></asp:TextBox>
<label for="rank">rank</label>
<asp:TextBox runat="server" ID="rank"></asp:TextBox>
</div>
<div>
<label for="assignment">assignment</label>
<asp:TextBox runat="server" ID="assignment"></asp:TextBox>
<label for="regular_shift">regular shift</label>
<asp:TextBox runat="server" ID="regular_shift"></asp:TextBox>
</div>
<div>
<label for="contact_phone">contact phone</label>
<asp:TextBox runat="server" ID="contact_phone"></asp:TextBox>
<label for="phone_type">phone type</label>
<asp:DropDownList ID="phone_type" runat="server">
<asp:ListItem>home</asp:ListItem>
<asp:ListItem>cell</asp:ListItem>
</asp:DropDownList>
<label for="email">sfpd email</label>
<asp:TextBox runat="server" ID="email" TextMode="Email"></asp:TextBox>
</div>
<div>
<asp:Button runat="server" ID="save" Text="update profile" />
</div>
</form>
</body>
</html>
Here is the c# code I have written to populate the TextBox "first_name":
protected void Page_Load(object sender, EventArgs e)
{
//show user logged in
if (Session["New"] != null)
{
userloggedin.Text = Session["New"].ToString();
}
//else redirect to login
else
Response.Redirect("Login.aspx");
SqlConnection conn = new SqlConnection(Connection-String);
SqlDataReader profileReader = null;
string userDataQuery = "SELECT * FROM dbo.users WHERE username ='" + userloggedin.Text + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(userDataQuery, conn);
profileReader = cmd.ExecuteReader();
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"].ToString();
}
conn.Close();
}
Thanks for your help
solved my own problem. The issue was in the column names of my database. my naming convention used underscores in the column names, however I omitted the underscore for the column in question. Rather than 'first_name' as it should have been, it was 'first name'.
If You are retrieving Only FirstName then There is no need to use *
try like this
string userDataQuery = "SELECT first_name FROM dbo.users
WHERE username ='" + userloggedin.Text + "'";
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"]==DBNull.Value ? "":
profileReader["first_name"].ToString();
}
Beware of SQL Injection Always Use SqlParameter
I'm trying to get gridview data using jquery. I have modified existing data on textbox and try to get that value using jquery. but it gave old value in textbox. not modified value in textbox.
ASPX Code
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
/*javascripts and stylesheets are here*/
<script type="text/javascript">
function Navigate() {
$('#dialogDiv').dialog('open');
}
$(document).ready(function () {
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="dialogDiv" title="Type" style="overflow: hidden">
<div id="TypeDiv" class="divTable">
<div class="divRow">
<div class="divColumn">
<div>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="open" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="Type_GV" runat="server" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:TextBox ID="txtType" runat="server" Text='<%# Bind("Type") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="open" runat="server" Text="Open dialog" OnClientClick="Navigate()"
OnClick="open_Clicked" />
<br />
<p>
<asp:Button ID="btnSaveType" runat="server" OnClick="btnSaveType_Clicked" Style="visibility: hidden;
display: none;" />
</p>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void open_Clicked(object sender, EventArgs e)
{
VehicleType vTypeObject = new VehicleType();
Type_GV.DataSource = vTypeObject.GetTypeList();
Type_GV.DataBind();
}
protected void btnSaveType_Clicked(object sender, EventArgs e)
{
foreach (GridViewRow gvr in Type_GV.Rows)
{
TextBox type = (TextBox)gvr.FindControl("txtType");
Debug.WriteLine("type : " + type.Text);
}
}
public class VehicleType
{
public string Type { get; set; }
public List<VehicleType> GetTypeList()
{
List<VehicleType> list = new List<VehicleType>()
{
new VehicleType{Type="Type1"},
new VehicleType{Type="Type2"}
};
return list;
}
}
How can i solve this ?
You may use this:
As you are using the update panels, this.remove_endRequest() is raised after an asynchronous postback is finished and control has been returned to the browser.
Not sure but i think this the issue, i faced these kind of issues many times. Might be helpful to you.
See Documentation
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest($(function(){
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});)
Note: Don't remove $(document).ready(function{})) keep it as it is, and include this one.
On my webpage, I have a CheckBoxList and a single checkbox. When I click on the check box, all the Check Boxes in the CheckBoxList should get checked. My CheckBoxList has to be under Bodycontent placeholder because that's how the layout of webpage is, and I kept the script in the same placeholder.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
function select(ch) {
var allcheckboxes = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName("input");
for (i = 0; i < allcheckboxes.length; i++)
allcheckboxes[i].checked = ch.checked;
}
</script>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allCheck" onclick="select(this)" runat="server" Text="Select all" />
<br />
</asp:Content>
The above doesn't do anything. On clikcing on the checkbox nothing happens! I have been stuck on this small issue from quite long and not able to do the same. Any suggestions what's wrong?
change the name of your function to something else; it will work
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
function select1(ch) {
var allcheckboxes = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName("input");
for (i = 0; i < allcheckboxes.length; i++)
allcheckboxes[i].checked = ch.checked;
}
</script>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allCheck" onclick="select1(this)" runat="server" Text="Select all" />
<br />
</asp:Content>
try like this..
function UnCheckAll(isCheck) {
var theForm = document.forms['yourFormName'];
if (!theForm) {
theForm = document.form1;
}
var length = theForm.elements.length;
for (var i = 0; i < length; i++) {
if (theForm.elements[i].type == "checkbox") {
if (theForm.elements[i].id != "allCheck") {
if (theForm.elements[i].disabled == false) {
theForm.elements[i].checked = isCheck.checked;
}
}
}
}
}