Binding objects to HTML TextBoxes in ASP.NET - c#

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
// ...
}

Related

Get text/value from textbox after value/text changed server side

I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}
In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}
with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).
In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.

A pragmatical point of view to ASP.NET's page cycle

I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.
In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)

Change div things in other page

I used the code below to make a change in div of the page of this code file:
HtmlGenericControl divTest = Page.FindControl("test") as HtmlGenericControl;
divTeste.InnerText = "tested";
But now, I want to change another page. Ex.: default.aspx code behind changes a div inner text in the test.aspx ...
The code above isn't appropriated. I want permanent changes. What code should be?
How can I do it?
You need to understand how ASP.NET works. Introduction to ASP.NET
If you are on Default.aspx and then wont to move to Test.aspx you can use values from Default.aspx in Test.aspx however you can't just change different pages from the page you are on. (Actually it is possible by writing data to a database and then later accessing that data on the page you want to change but for your example I don't believe you are looking for something like that)
The closest to your example I can think of is using a Query string.
Default.aspx Markup
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Default.aspx Code behind
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Test.aspx?DivMSG=Hello");
}
Test.aspx Markup
<div id="MyTestDiv" runat="server">
</div>
Test.aspx Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyTestDiv.InnerText = Request.QueryString["DivMSG"];
}
}
Update:
One way to make it permanent is to write it to a database. A quick example but you need to do the database code
Default.aspx Markup
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Default.aspx Code behind
protected void Button1_Click(object sender, EventArgs e)
{
string messageToWriteToTestDiv = TextBox1.Text;
// Code: to write messageToWriteToTestDiv to the database
}
Test.aspx Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string myMessage = "";
// Code: string myMessage = Get Message from Database to write to div
MyTestDiv.InnerText = myMessage;
}
}
Test.aspx Markup
<div id="MyTestDiv" runat="server">
</div>

How to assign the selected value of Drop down to text box

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;
}
}

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.

Categories

Resources