Tuesday, March 27, 2012

Binding data to text box

I want to bind some data to a text box from sql server db. but when i run the page i get an error. here is my code.

<formid="form1"runat="server"><div><asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:imacsConn %>"SelectCommand="SELECT Reportnumber FROM [SummaryBlue] WHERE REPORTNUMBER = @.REPORTNUMBER"><SelectParameters><asp:QueryStringParameterName="REPORTNUMBER"QueryStringField="REPORTNo"Type="String"/>

</SelectParameters></asp:SqlDataSource><asp:TextBoxID="TextBox1"runat="server"Columns="<%$ ConnectionStrings:imacsConn %>"></asp:TextBox></div></form>

Error:

Exception Details:System.FormatException: Input string was not in a correct format.

Source Error:

Line 25: </SelectParameters>Line 26: </asp:SqlDataSource>Line 27: <asp:TextBox ID="TextBox1" runat="server" Columns="<%$ ConnectionStrings:imacsConn %>"></asp:TextBox></div>Line 28: </form>

The Columns property of a text box is how many characters wide it should be (an integer property). You are trying to assign it a string.

<asp:TextBoxID="TextBox1"runat="server"Columns="<%$ ConnectionStrings:imacsConn %>">

|||

Hi xbhavesh,

From your description, I understand you want to bind data to single TextBox. Base on my experience and research, SqlDataSource can be binded to List data-bound controls, but TextBox is not belong to them. So I think we cannot simply bind data to TextBox from SqlDataSource.

I find two solutions and hope they are helpful to you.

1. Bind the DataSource to a GridView, and then bind the GridView cell value to TextBox. Don't forget set GridView to not visible and call DataBind method when Page Load. Here is the sample code:

<asp:TextBoxID="TextBox1"runat="server"Text='<% #GridView1.Rows[0].Cells[0].Text%>'></asp:TextBox>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:testConnectionString%>"

SelectCommand="SELECT [id] FROM [Table1] WHERE ([id] = 2)">

</asp:SqlDataSource>

<asp:GridViewID="GridView1"Visible="false"runat="server"DataSourceID="SqlDataSource1">

</asp:GridView>

protectedvoid Page_Load(object sender,EventArgs e)

{

TextBox1.DataBind();

}

2. Create your custom control to inherit DataBoundControl:

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.databoundcontrol.aspx

P.S. We should bind to the Text property, not Columns.

No comments:

Post a Comment