How to assign the selected value of Drop down to text box - c#

I'm trying to assign the selected value in the drop down to text box when ever I hit a button. I'm not able to see the selected value in the TextBox. Can someone please let me know what am I missing?
My code is as follows:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string strConn = "Initial Catalog=NavigateV6;Data Source=SVUSRYE-SQL3D1;User ID=dopis_user;Password=dopis_password;Persist Security Info=True;MultipleActiveResultSets=True";
SqlConnection mycn = new SqlConnection(strConn);
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select accountid FROM trn_account ", mycn);
myda.Fill(ds);
DDL.DataSource = ds;
DDL.DataTextField = "AccountID";
DDL.DataValueField = "AccountID";
DDL.DataBind();
}
protected void DDL_SelectedIndexChanged(Object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(TextBox1.Text))
TextBox1.Text = selectedValue;
}
}
ASPX:
<asp:DropDownList ID="DDL" runat="server" AutoPostBack="True" OnSelectedIndexChanged = " DDL_SelectedIndexChanged" >
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
Text="sumbit" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</asp:Content>

jQuery can do that in a snap without a postback:
$('#<%= ButtonID.ClientID %>').click(function() {
$('#<%= TextBoxID.ClientID %>').val($('#<%= DDL_ID.ClientID %>').val());
return false;
});
In fact you don't even need to click a button, it can be done when the user selects a new value in the ddl:
$('#<%= DDL_ID.ClientID %>').change(function() {
$('#<%= TextBoxID.ClientID %>').val($(this).val());
});

Your problem is because when when you check (!string.IsNullOrEmpty(TextBox1.Text)), it always return false because at first stage, value of TextBox is empty and hence never execute inner code of if condition.....If you need to go through above condition, you can put some value in TextBox at the time of declaration.......
Or,
Simply do like this in SelectedIndexChanged of DropDownList
var selectedValue = ((DropDownList)sender).SelectedValue;
TextBox1.Text = selectedValue;
Here is working example as like your code:
ASPX:
<body>
<form runat="server" id="form1">
<asp:DropDownList ID="DDL" runat="server" AutoPostBack="True"
OnSelectedIndexChanged = "DDL_SelectedIndexChanged" >
<asp:ListItem Value="One">One</asp:ListItem>
<asp:ListItem Value="Two">Two</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="sumbit" onclick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</form>
</body>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
TextBox1.Text = selectedValue;
}
}

Related

Binding objects to HTML TextBoxes in ASP.NET

Is this the right way to bind an object to TextBox in ASP.NET? I'm new to it. I want to get and set data to these text boxes from a database?
txtusername.Value = objBO_MstrUsers.UserName;
txtPassword.Value = objBO_MstrUsers.UserPassword;
TxtUserlevel.Value = objBO_MstrUsers.UserLevel.ToString();
txtUserPhno.Value = objBO_MstrUsers.UserPhone;
txtUserEmail.Value = objBO_MstrUsers.UserEmail;
I want to get and set data to these text boxes from a database.
Assuming you have a simple WebForms page such as:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
</div>
</form>
this should work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// populate control with database value
txtUsername.Text = objBO_MstrUsers.UserName;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// get data from control
objBO_MstrUsers.UserName = txtUsername.Text;
// do anything with the data, e.g. store in database
// ...
}

ASP.NET checkbox autopostback not working

I designed a simple page with, two text boxes, one checkbox, one button, and one label.
When I start I want to check the checkbox to make the button enabled, and then enter two numbers into the two textboxes, click the button to do addition, and show the result in the label.
But when I click the checkbox the page postback is not working; it's not writing Page is posted back on the page and the button is still disabled.
However, if I make the button enabled and do the addition it invokes the page postback and also invokes the checkedchanged method.
<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<asp:Label ID="result" runat="server"></asp:Label>
<td>
<asp:CheckBox ID="cboptions" runat="server" AutoPostBack="True"
onCheckedChanged="cboptions_CheckedChanged" />
</td>
<asp:Button ID="submit" runat="server" Text ="addition" onclick="Button_Click"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
Response.Write("Page is posted back");
}
}
protected void cboptions_CheckedChanged(object sender, EventArgs e)
{
submit.Enabled = cboptions.Checked;
}
protected void submit_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirst.Text);
int b = Convert.ToInt32(txtSecond.Text)+a;
result.Text = b.ToString();
}
There were many formatting errors in your code, do it this way
Aspx
<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<asp:Label ID="result" runat="server"></asp:Label>
<asp:CheckBox ID="cboptions" runat="server" AutoPostBack="True"
onCheckedChanged="cboptions_CheckedChanged" />
<asp:Button ID="btn" runat="server" Text ="addition" onclick="Button_Click"/>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
Response.Write("Page is posted back");
}
}
protected void cboptions_CheckedChanged(object sender, EventArgs e)
{
btn.Enabled = cboptions.Checked;
}
protected void Button_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirst.Text);
int b = Convert.ToInt32(txtSecond.Text) + a;
result.Text = b.ToString();
}

List created in OnInit not persisting

I having a problem maintaining a list of strings. The list is instantiated in OnInit and set as the data source for a GridView. (The basic idea is that the user enters something in the text box, and it appears in the GridView, as many times as they want.)
It works just fine for the first entry, whatever the user enters shows up in the GridView, pretty as can be. However, on following entries, any previously entered values disappear - OnInit is executed again, the List<string> is re-instantiated, and the previous values are over-written. I tried moving the OnInit logic into OnPreInit but just got a Null Reference Exception on the list.
Here's a contrived example of what I'm trying to do:
I have a TextBox, a Button and a Gridview:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add"
onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="true"></asp:GridView>
In the code behind:
protected override void OnInit(EventArgs e)
{
List<string> gvValues = new List<string>();
GridView1.DataSource = gvValues;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
gvValues.Add(TextBox1.Text);
GridView1.DataBind();
}
I've created objects in OnInit in the past, and haven't had a problem with their state persisting. Obviously I'm missing something here. Someone please point out the flaw in my logic and suggest a method for achieving this functionality.
The below code is tested an it works.
// ASPX Code
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add"
onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="true"></asp:GridView>
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> gvValues = new List<string>();
GridView1.DataSource = gvValues;
GridView1.DataBind();
Session["Data"] = gvValues;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<string> lt = new List<string>();
lt = (List<String>)Session["Data"];
lt.Add(TextBox1.Text);
GridView1.DataSource = lt;
GridView1.DataBind();
Session["Data"] = lt; // Save it in Session, so next time available
}
// Add the values one by one, and it will show you all the values
// OUTPUT
Test
Test1
Test2
Have you tried to reassign the list to the gridview and put the gvValues into the session:
protected override void OnInit(EventArgs e)
{
GridView1.DataSource = GvValues;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
GvValues.Add(TextBox1.Text);
GridView1.DataSource = GvValues;
GridView1.DataBind();
}
private List<string> GvValues
{
get
{
if(Session["list"] != null)
{
return (List<string>)Session["list"];
}
return new List<string>();
}
set
{
Session["list"] value;
}
}
I did a small example which worked fine for me
default.aspx
<form id="form1" runat="server">
<asp:GridView ID="gvEntries" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<asp:TextBox ID="txtNewEntry" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save entry" OnClick="btnSave_Click" />
</form>
default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> source = new List<string>();
source.Add("entry1");
source.Add("entry2");
source.Add("entry3");
Session["source"] = source;
gvEntries.DataSource = source;
gvEntries.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
List<string> source = (List<string>)Session["source"];
source.Add(txtNewEntry.Text);
gvEntries.DataSource = source;
gvEntries.DataBind();
}
This example binds your initial data on pageLoad (GET). So your datasource is stored within the gridviews viewstate. If you want to add another entry you have to access your original source - which has been stored within a Session-var. So get a reference to it, add a value, and rebind your dataSource.

Running a C# and a Javascript function on an asp button control?

I can get both the Javascript and the C# function to work just fine.
However, my Javascript function runs before the C#.
How do I get it to run after the C# function??
Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
OnClientClick="javascript:Highlit()" />
</div>
</asp:View>
</asp:MultiView>
<script type="text/javascript">
function Highlit()
{
$("#div2").effect("highlight", {}, 10000);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
}
}
Here is the code reflecting changes from the answers:
Code behind
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "TEST", "Highlit();", true);
}
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function Highlit() {
$("#div2").effect("highlight", { color: "#9499FC" }, 10000);
}
</script>
The only way to get the javascript to run after is to add a script reference in your Button1_Click event.
Example Code for standard postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
As noted by others, be sure to remove your OnClientClick event. Also, consider moving your "Highlit" script outside of the update panel.
Additionally, since you are in an update panel, you will need to use the following example code for a Partial Postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
You have to register a ClientScript at the end of Button1_Click event
and remove OnClientClick="javascript:Highlit()"
protected void Button1_Click(object sender, EventArgs e)
{
//Do stuff
ScriptManager.RegisterStartupScript(this, this.GetType(), "ANYNAME", "javascript:Highlit();", true);
}
Remove the OnClientClick attribute, and add the call as a startup script, so that it runs after the page has loaded:
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "start", "Highlit();", true);
}
Side note: When you use the OnClientClick attribute, the code should not start with javascript:. That's only used when you put script in a href attribute in a link.

Copying the entire telerik docklayout from one page to another page

I'm trying to copy the docklayout from one page and try to recreate it in another page.
Here is my code-
Default.aspx
<div>
<telerik:RadDockLayout ID="dockLayout" runat="server" OnSaveDockLayout="dockLayout_SaveDockLayout">
<telerik:RadDockZone ID="dockZone" runat="server">
<telerik:RadDock ID="dock" runat="server" UniqueName="dock1">
<Commands>
</Commands>
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server" Text="Dock1"></asp:TextBox>
<br />
<asp:Button ID="btnOK" runat="server" Text="OK1" />
</ContentTemplate>
</telerik:RadDock>
</telerik:RadDockZone>
<br /><br />
<telerik:RadDockZone ID="RadDockZone1" runat="server">
<telerik:RadDock ID="RadDock1" runat="server" UniqueName="dock2">
<Commands>
</Commands>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text="Dock2"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="OK2" />
</ContentTemplate>
</telerik:RadDock>
</telerik:RadDockZone>
</telerik:RadDockLayout>
<div style="width:100%;text-align:center">
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</div>
</div>
Default.aspx.cs
protected void dockLayout_SaveDockLayout(object sender, DockLayoutEventArgs e)
{
List<DockState> dockState = dockLayout.GetRegisteredDocksState();
JavaScriptSerializer ser = new JavaScriptSerializer();
Session["dock"] = ser.Serialize(dockState);
}
protected void btnSave_Click(object sender, EventArgs e)
{
Response.Redirect("receivingPage.aspx");
}
receivingPage.aspx.cs
public partial class receivingPage : System.Web.UI.Page
{
private List<DockState> dockStates;
private RadDockLayout dockLayout;
protected override void OnInit(EventArgs e)
{
dockLayout = new RadDockLayout();
dockLayout.LoadDockLayout += new DockLayoutEventHandler(dockLayout_LoadDockLayout);
JavaScriptSerializer ser = new JavaScriptSerializer();
dockStates = ser.Deserialize<List<DockState>>(Page.Session["dock"].ToString());
for (int i = 0; i < dockStates.Count; i++)
{
RadDock dock = new RadDock();
dock.ID = string.Format("RadDock{0}", i);
dock.ApplyState(dockStates[i]);
dockLayout.Controls.Add(dock);
}
this.Controls.Add(dockLayout);
}
protected void Page_Load(object sender, EventArgs e)
{
}
void dockLayout_LoadDockLayout(object sender, DockLayoutEventArgs e)
{
foreach (DockState state in dockStates)
{
e.Positions[state.UniqueName] = state.DockZoneID;
e.Indices[state.UniqueName] = state.Index;
}
}
}
But I'm getting emtpy docklayout in receivingPage.aspx. Any ideas?
I would suggest to contact Telerik via the forum or to send a support ticket with a sample project.

Categories

Resources