what's the right way to bind sqldatasource to asp:label in asp.net 4.0?
Is it possible using Eval? If so, can someone post a short fragment to illustrate? My SqlDataSource returns 1 record with 3 fields, I'd like to Format these into a string. eg:
Record Field 'Name' = 'Jack' Field 'Amount' = 100 Field 'Date' = 12.02.2010
asp:Label text should end up being:
Welcome Jack, last payment was 100 on 12.02.2010
if another control than asp:Label is appr开发者_开发知识库opriate, that would be good to know also.
Label's the right control for what you want to display, but SqlDataSource probably isn't the right control for getting the data. Labels have no DataSourceID property that allows you associate the controls together - whilst you might be able to do some plumbing in your server-side code to make it work, my suspicion is it'd be more efficient to get the relevant DataRow during Page_Load, build the string and then put that into the Text property of the Label.
Thanks for the steer Phil, this is my solution (error checking to do, critique welcome):
private void DataSourceIntoLabel(Label label,
SqlDataSource dataSource,
ParameterCollection parameters,
string formatString,
string[] columnNames)
{
dataSource.SelectParameters.Clear();
foreach (System.Web.UI.WebControls.Parameter p in parameters)
{
dataSource.SelectParameters.Add(p);
}
IEnumerable rows = dataSource.Select(DataSourceSelectArguments.Empty);
IEnumerator enumerator = rows.GetEnumerator();
enumerator.MoveNext();
DataRowView rowView = (DataRowView)enumerator.Current;
label.Text = string.Format(formatString, rowView.Row.ItemArray);
}
精彩评论