Tuesday, March 27, 2012

Binding a SqlDataSource to a TextBox or label

I have a SQL database with 1 column in it.. it is a do not call registry for my office. I want to make a web application so our leads can go on the web and request to be put on the do not call list. problem is, if their number already exists, it gets a violation of primary key...

Normal handling for this would be to do a select query based on user input, and if it exists in the database, tell them that, else do the insert query...

Problem is, i cant seem to figure out how to bind the result of the select query to a textbox or label so i can compare the results to do that logic. Any ideas? This is in asp .net 2.0. Thanks!

-Dan

You can't directly bind to a Label or a TextBox, but you certainly can set the result of your DataSource to the Text property of your control. Here's an example:

ASPX

ProductName = <asp:label id="lblProductName" runat="server" /><asp:objectdatasource id="odsProducts" runat="server" selectmethod="GetProductByProductID"typename="NorthwindTableAdapters.ProductsTableAdapter"><selectparameters><asp:parameter defaultvalue="1" name="ProductID" type="Int32" /></selectparameters></asp:objectdatasource>

CODE-BEHIND

protected void Page_Load(object sender, EventArgs e){if (!this.IsPostBack){DataView dv = (DataView)odsProducts.Select();lblProductName.Text = dv[0]["ProductName"].ToString();}}

|||

Acctually... i figured out a way... check this out..

Dim dv As Data.DataView = SqlDataSource1.Select(DataSourceSelectArguments.Empty)

TextBox1.Text = dv.ToTable.Rows(0)("PHONE")

This works, but now i have another problem. If there is no row 0 (meaning if the number doesnt exist) the page fails. How can i check to see if the record doesnt exist, then do something else?

|||Just check to see if the DataView.Count property is greater than 0.|||Thanks, that worked great!

No comments:

Post a Comment