ZeeeeeV
ZeeeeeV

Reputation: 381

C# Binding Data to Text Box

I am trying to bind a database row to a text box in C# so it is the default value (but the text box can still be edited).

The current issue i am having is that the text box will not let me attach a data source with the error (System.Web.UI.WebControls.TextBox does not contain a definition for 'DataSource'....)

I am able to succesfully bind the datasource to a drop down list, but using the same code for a text box does not work.

        txtBox1.DataSource = "DataSource";
        txtBox1.DataBind();

Upvotes: 2

Views: 22238

Answers (5)

Vintage Coder
Vintage Coder

Reputation: 501

Note: TextBox Control alone doesn't have the Datasource property.

If TextBox control is used inside the item template of Databound controls like GridView,DataGrid,ListView,DetailsView,FormView, you can used the eval,bind,xpath based on that chosen datasource like sql,xml,object etc..

Eg,

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("TITLE")%>'> </asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("TITLE")%>'> </asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# XPath("TITLE")%>'> </asp:TextBox>

If TextBox control is used alone or outside of databound controls, you can use in the below format.

<asp:TextBox ID="TextBox1" runat="server" Text='<%#TITLE%>'> </asp:TextBox>

in code behind file, simply use in any of the page lifecycle events.

this.Page.Databind();

Upvotes: 0

Igoy
Igoy

Reputation: 2962

DataView dv = DataSource.DefaultView;

dv.RowFilter = "id=1"; // or whatever as per your need to make sure only 1 row is there
textBox1.DataBindings.Add("Text",dv,"id");

Upvotes: 0

Luis Tellez
Luis Tellez

Reputation: 2993

If you want to set a Value to the text box what you need to do is :

textBox1.Text= "MyText";

then the user can change that value and on the postback you use that value for whatever you need and the user

Upvotes: 1

Echilon
Echilon

Reputation: 10264

You can't bind a DataSource to a TextBox in WebForms. You can set the text to a field in a DataRow using the indexer.

`txtBox1.Text = datarow["SomeField"]`

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

The reason for that is that a DataSource contains multiple rows. A drop down can support that, as it will show one entry per row, but a TextBox doesn't support it. There is only one text field, which row from the data source should it use?

To set the text of a TextBox use the Text property.

Upvotes: 2

Related Questions