Friday, February 24, 2012

Accessing value from SqlDataSource

I have a SqlDataSource that returns a list of companies and their details by ProductID. It also returns the name of the product associated with the ProductID as the final column (which means it appears for every record returned). I already have a way of determining how many rows were returned, and use that information in a label to say "Your search has returnedx records".

protected void dsGetSuppliersByProduct_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
int RecordCount = e.AffectedRows;
if (RecordCount == 0)
{ lblRecordCount.Text = "<p>No Records found"; }
else
{
if (RecordCount == 1)
{ lblRecordCount.Text = "<p>Your search returned 1 record"; }
else
{ lblRecordCount.Text = "<p>Your search returned " + RecordCount + " records"; }
}
string ProductName;
}

How can I access the ProductName value so that I can extend the label text to say "Your search has returnedx records for <ProductName>" ?

I found a way to do what I wanted. I changed the label to a literal control (for display purposes) and accessed the ProductName value in the RowDataBound event. I then applied it to another literal. My first go resulted in the ProductName appearing as many times as there were rows, so I checked to see if the Literal.Text had already been assigned. So now my code looks like this:

protected void dsGetSuppliersByProduct_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
int RecordCount = e.AffectedRows;
if (RecordCount == 0)
{ ltRecordCount.Text = "<p>No Records found"; }
else
{
if (RecordCount == 1)
{ ltRecordCount.Text = "<p>1 supplier"; }
else
{ ltRecordCount.Text = "<p>" + RecordCount + " suppliers"; }

}

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string pName = DataBinder.Eval(e.Row.DataItem, "ProductName").ToString();
if (ltProductName.Text == "")
{
ltProductName.Text = " of <strong>" + pName + "</strong></p>";
}
}
}

No comments:

Post a Comment