Problem: I have an asp.net Textbox that I am putting text into and on text change it should assign its value to a variable, this does not happens.
Question: What is the best method to retrieve the value from the Textbox?
C# Code:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
protected void txtSourceServer_TextChanged(object sender, EventArgs e)
{
SourceString.DataSource = txtSourceServer.Text;
}
protected void txtSourceDatabase_TextChanged(object sender, EventArgs e)
{
SourceString.InitialCatalog = txtSourceDatabase.Text;
}
protected void txtSourceUN_TextChanged(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
}
protected void txtSourcePass_TextChanged(object sender, EventArgs e)
{
SourceString.Password = txtSourcePass.Text;
}
Asp.Net Code:
<table style="width: 100%;Border:1px solid Black;">
<tr>
<td class="style1">
Source Server:</td>
<td class="style1">
<asp:TextBox ID="txtSourceServer" runat="server"
ontextchanged="txtSourceServer_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Source Database:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceDatabase" runat="server"
ontextchanged="txtSourceDatabase_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
User Name:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceUN" runat="server"
ontextchanged="txtSourceUN_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Password:
</td>
<td class="style1">
<asp:TextBox ID="txtSourcePass" runat="server"
ontextchanged="txtSourcePass_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
<asp:Button ID="btnSourceConnect" runat="server" Text="Test Connection"
onclick="btnSourceConnect_Click" />
</td>
</tr>
</table>
What is the best method to retrieve the value from the Textbox?
The best method is like this control I am writing right now, you have a button that make post back, and then you read the value of the text box on code behind - on post back.
Using the AutoPostBack="True" on every TextBox you use involves too many unnecessary post backs to the server, it is better to use a "submit" button and save all your values when the user click on submit.
In you case you have a button, and you only need to remove the auto post back and set your values only when you try to connect as:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
SourceString.DataSource = txtSourceServer.Text;
SourceString.InitialCatalog = txtSourceDatabase.Text;
SourceString.Password = txtSourcePass.Text;
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
AutoPostback = true on a TextBox will cause the page to post back when the text box loses focus, not on every text change.
From the look of your code most of this functionality should be happening on the client side (i.e. with javascript).
Related
I have 8 items in a SQL table with a Description, ItemNumber, and ImagePath.
protected void Page_Load(object sender, EventArgs e)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
I am using a DataList to show all of the items along with a textbox that will allow a user to input the number of items they want:
<asp:DataList ID="SignsList" runat="server" RepeatColumns="4" CellPadding="2" Width="90%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<table>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "Description") %>
</th>
</tr>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "ItemNumber") %>
</th>
</tr>
<tr>
<td>
<asp:Image ID="SignImage" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "ImagePath") %>' />
</td>
</tr>
<tr style="text-align: center;">
<td>
<asp:TextBox ID="txtSignQuantity" runat="server" CssClass="txtBox" BackColor="White" Enabled="true"
type="number" min="0" ToolTip="Please choose quantity of signs needed."/>
</td>
</tr>
<tr>
<td>
<p> </p>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<div class="btnGroup">
<div class="btnDiv">
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btnSave" Width="90px" Visible="true" OnClick="btnSave_Click"/>
</div>
<div class="btnDiv">
<asp:Button ID="btnCancel" runat="server" Text="Clear" CssClass="btnCancel" Width="90px" Visible="true" OnClick="btnCancel_Click"/>
</div>
</div>
After the saved button is clicked in C# I want to find out the value that a user entered but it is always returning null:
protected void btnSave_Click(object sender, EventArgs e)
{
TextBox txtSignQuantity;
string tempSignQuantity;
try
{
foreach (DataListItem item in SignsList.Items)
{
txtSignQuantity = item.FindControl("txtSignQuantity") as TextBox;
tempSignQuantity = txtSignQuantity.Text;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I also checked and the Count of SignsList.Items was 8, so I know that it is retrieving the correct information. Sorry, I've never used a Data List before so I'm not really sure how to go about this...
The short answer is that data binding on postback is causing the problem. Check the Page.IsPostBack property before doing data binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
}
ASP.NET WebForms attempts to abstract away the fact that the control instances that were used to render the page are not the same instances it has when handling postback events. Data binding compounds the abstraction because it has to create controls in response to the DataBind call, and then on postback, recreate them based on the ViewState it saved.
Initializing controls from ViewState happens on the Init event, so when the Load event is fired later in the page lifecycle and you call DataBind on the control, everything it restored gets wiped out and recreated.
As for why you were getting null, it may have been that the controls were wiped out but not recreated; it may have had to do with other event handlers that didn't get rewired after the second data binding.
I want to persist user control values
If I add one more rows the previous control values is not there
I gone through some sites but I'm not able to understand clearly
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ControlCount"] = ViewState["ControlCount"] == null ? 2 : ViewState["ControlCount"];
}
}
public int controlCount
{
get
{
int val = 0;
try
{
val = (int)ViewState["ControlCount"];
}
catch (Exception e)
{
// handle exception, if required.
}
return val;
}
set { ViewState["ControlCount"] = value; }
}
Here I am adding the User controls
protected void addnewtext_Click(object sender, EventArgs e)
{
int i = controlCount++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
Label lb = new Label();
string z = Convert.ToString(j + 1);
lb.Text = "Visa " + z;
rpt1.Controls.Add(lb);
lb.Attributes.Add("class", "style8");
rpt1.Controls.Add(ac);
rpt1.Controls.Add(new LiteralControl("<BR>"))
}
}
AddVisaUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>
The dynamic controls must be added on every postback, so that ViewState can maintain its values. For more details, please read the ASP.NET page life cycle.
I've have one table, in that table within one I've one and within that , I've update panel whose update mode is set to conditional. Within this update panel I've another table. The table contains 3 text boxes as: old password, new password and confirm password. On the textChanged event of the old password I am checking the user entered value with the value in db. But when the function completes its execution all the 3 text boxes looses its values regardless of whether I update the update panel or not. I don't know why it clears text boxes. I want to prevent text boxes from getting cleared. I tried to get the text box text in string variable and again assign it to text boxes (both in text box text changed event and in page load event under isPostBack condition) but its too, not working.
asp code:
.
.
.
<tr>
<td colspan="3">
<div>
<asp:UpdatePanel ID="updPnlChngPwd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:100%">
<tr>
<td>
Old Password
</td>
<td>:</td>
<td>
<asp:TextBox ID="txtOldPwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%" ontextchanged="txtOldPwd_TextChanged"
AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:Label ID="lblWrongOldPwd" runat="server" Text="Wrong Old Password" ForeColor="Red" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>:</td>
<td></td>
</tr>
<tr>
<td></td>
<td>:</td>
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnUpdPwd" runat="server" Text="Change Password" onclick="btnUpdPwd_Click"/></td>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<td>
</tr>
.
.
.
C# code for tetxt box textChanged event:
protected void txtOldPwd_TextChanged(object sender, EventArgs e)
{
DataTable dtOldPwd = Obj.DBAccess("select Pwd from Customer where Cust_Id = " + Convert.ToInt32(Session["SuppID"]) + " and Supp_Pwd = '" + txtOldPwd.Text + "'");
if (dtOldPwd.Rows.Count == 1)
{
lblWrongOldPwd.Visible = false;
}
else
{
lblWrongOldPwd.Visible = true;
updPnlChngPwd.Update();
}
}
Now I am not able to understand what exactly wrong I am doing, does having update panel inside the table causing problem?
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
You have TextMode set to password which will not save your textbox value .
However you will get your textbox value as string on textchange event
protected void txtbx_TextChanged(object sender, EventArgs e)
{
string txtValue = txtbx.Text;
ViewState["xyz"]= txtValue;
}
and you have to save this value in ViewState to use it for btnClick event .
OR
You can also set textbox attribute at Page_Load event which is a very bad practice to do like this
protected void Page_Load(object sender, EventArgs e)
{
txtbx.Attributes.Add("value", txtbx.Text);
TextBox with TextMode="Password" will be cleared after postback or partial postback. This is the default behavior of the password textbox so submit all the data at a time and do the validation in your code.
Alternatively, You can store password in in viewstate or session and restore after postback.
I have a ASPxNavBar control in my project. It has some NavBarGroup which has contenttemplate.
Hasta Tc Kimlik No:
Ad:
</dx:ASPxTextBox>
</td>
</tr>
<tr>
<td>
Soyad:
</td>
<td>
<dx:ASPxTextBox ID="txtHastaSoyad" runat="server" Width="170px">
</dx:ASPxTextBox>
</td>
</tr>
</table>
</ContentTemplate>
</dx:NavBarGroup>
......................
I want to get NavBarGroup and set its control's value.
Hasta hasta = new Hasta(Session["hasta_id"].To<int>());
NavBarGroup hastaGrup = nbDiyalizBildirim.Groups.FindByName("hasta");
((ASPxTextBox)hastaGrup.FindControl("txtHastaTCkimlikNo")).Text = hasta.M_TcKimlikNo;
((ASPxTextBox)hastaGrup.FindControl("txtHastaAd")).Text = hasta.M_Adi;
((ASPxTextBox)hastaGrup.FindControl("txtHastaSoyad")).Text = hasta.M_Soyadi;
How can i set their values?
Thanks in advance.
The following code works fine here:
protected void ASPxNavBar1_PreRender(object sender, EventArgs e) {
ASPxNavBar navBar = sender as ASPxNavBar;
ASPxTextBox txtBox = navBar.Groups[0].FindControl("txtBox") as ASPxTextBox;
txtBox.Text = "some test string";
}
Here is the aspx markup:
<dx:ASPxNavBar ID="ASPxNavBar1" runat="server" OnPreRender="ASPxNavBar1_PreRender">
<Groups>
<dx:NavBarGroup>
<ContentTemplate>
<dx:ASPxTextBox ID="txtBox" runat="server"></dx:ASPxTextBox>
</ContentTemplate>
</dx:NavBarGroup>
</Groups>
</dx:ASPxNavBar>
In my project I am making one form which contains three dropdown lists each for company,department and vacancies with "Select" as their default text. I am feeling company dropdown list at form load event but default text is "Select" now when user select company, second list should be filled with departments of selected company but default text should be "select". Again when user select department,the third list should be filled with vacancies on the selected department of selected company but default text should be "select".
I am trying to fill other two dropdown list with "selected index change" event of company list and department list respectively. but its not working as I want.
Here is my code for .aspx page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table width="100%">
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td align="center" class="tdtitle" colspan="4">
Search Candidates
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td class="RowHeight" width="20%">
Select Company</td>
<td width="30%">
<asp:DropDownList ID="companyList" runat="server" AutoPostBack="True"
onselectedindexchanged="companyList_SelectedIndexChanged" Width="150px">
<asp:ListItem>-Select Company-</asp:ListItem></asp:DropDownList>
</td>
<td width="20%">
Select Department</td>
<td width="30%">
<asp:DropDownList ID="deptList" runat="server" AutoPostBack="True"
Width="150px" onselectedindexchanged="deptList_SelectedIndexChanged" onclick="Validate();">
<asp:ListItem>-Select Department-</asp:ListItem></asp:DropDownList>
</td>
</tr>
<tr>
<td class="RowHeight" width="20%">
Select Vacancy</td>
<td colspan="3" width="*">
<asp:DropDownList ID="vacanyList" runat="server" Width="200px">
<asp:ListItem>-Select Vacancy-</asp:ListItem></asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td align="center" colspan="4">
<asp:Label ID="notifyLbl" runat="server" Font-Size="Large" ForeColor="Red"
Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
</table>
<script type="text/javascript">
function alertOnBadSelection() {
var select = document.getElementById('companyList');
if (select.options[select.selectedIndex].value == "-Select Company-") {
alert('Please Select Company!');
return false;
}
}
</script>
</asp:Content>
/And below is the code for my .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class HR_Department_searcAppForVac : System.Web.UI.Page
{
DataOperation oDo = new DataOperation();
protected void Page_Load(object sender, EventArgs e)
{
// deptList.Attributes.Add("onchange", "alertOnBadSelection();");
notifyLbl.Visible = false;
if (!IsPostBack)
{
try
{
DataTable objCmpnyTable = oDo.DropDownList("select * from tblCompanyMaster");
if (objCmpnyTable.Rows.Count > 0)
{
foreach (DataRow Row in objCmpnyTable.Rows)
{
companyList.Items.Add(new ListItem(Row["CompName"].ToString(), Row["CompId"].ToString()));
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "There is not any company in the list.";
}
}
catch (Exception)
{
throw;
}
}
else
{
//deptList.SelectedIndex = -1;
//vacanyList.SelectedIndex = 1;
}
}
protected void companyList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (companyList.SelectedIndex > 0)
{
deptList.Items.Clear();
string str = "select * from vwCompWiseList where CompId=" + companyList.SelectedValue;
DataTable objDeptTable = oDo.DropDownList("select DeptId,DeptName from vwCompWiseDept where CompId= "+companyList.SelectedValue);
if (objDeptTable.Rows.Count > 0)
{
foreach (DataRow Row in objDeptTable.Rows)
{
deptList.Items.Add(new ListItem(Row["DeptName"].ToString(), Row["DeptId"].ToString()));
}
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Company....";
}
}
catch (Exception)
{
throw;
}
}
protected void deptList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (deptList.SelectedIndex > 0)
{
vacanyList.Items.Clear();
DataTable objVacancytbl = oDo.DropDownList("select VacId,VacTitle from tblVacancyMaster where DeptId =" + deptList.SelectedValue + " and CompId=" + companyList.SelectedValue);
if (objVacancytbl.Rows.Count > 0)
{
foreach (DataRow Row in objVacancytbl.Rows)
{
vacanyList.Items.Add(new ListItem(Row["VacTitle"].ToString(), Row["VacId"].ToString()));
}
vacanyList.SelectedIndex = -1;
vacanyList.ClearSelection();
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Ops..!There is no available vacancy....";
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Department...";
}
}
catch (Exception)
{
throw;
}
}
}
Please show my problem and its solutions.
I think you may want to leverage jquery cascading drop downs . Using a cascading drop down javascript (jquery) will call back and reload dependent drop downs based on the value(s) selected in the previous drop down.