Reputation:
I am using Weather WebService and I have a gridview with the id forecast
. How could I display foreach items in the gridview? I have tried using
forecast += item.Date.ToShortDateString() + " " + item.Desciption + "|";
But I get the error
'System.Web.UI.WebControls.GridView' does not contain a definition for 'forecast' and no extension method 'forecast' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found (are you missing a using directive or an assembly reference?)
WeatherService.WeatherSoapClient weather = new WeatherService.WeatherSoapClient("WeatherSoap");
WeatherService.ForecastReturn for = weather.GetCityForecastByZIP(Zip.Text);
if (for.Success)
{
response.Text = for.ResponseText;
city.Text = for.City;
State.Text = for.State;
WeatherStationCity.Text = for.WeatherStationCity;
foreach (var item in for.ForecastResult)
{
forecast += item.Date.ToShortDateString() + " " + item.Desciption + "|";
}
Upvotes: 1
Views: 866
Reputation: 1216
Use the following code. ForecastItem
class should be defined in a separate file. And add two columns to your gridview, setting DataField
property of them to Date
and Description
(or set AutoGenerateColumns
to true)
public class ForecastItem
{
public string Date {get;set;}
public string Description {get;set;}
}
.
.
.
WeatherService.WeatherSoapClient weather = new WeatherService.WeatherSoapClient("WeatherSoap");
WeatherService.ForecastReturn for = weather.GetCityForecastByZIP(Zip.Text);
if (for.Success)
{
response.Text = for.ResponseText;
city.Text = for.City;
State.Text = for.State;
WeatherStationCity.Text = for.WeatherStationCity;
List<ForecastItem> forecastItems = new List<ForecastItem>();
foreach (var item in for.ForecastResult)
{
forecastItems.Add(new ForcastItem() {
Date = item.Date.ToShortDateString(),
Description = item.Desciption
});
}
forecast.DataSource = forecastItems;
forecast.DataBind();
}
Upvotes: 1
Reputation: 21795
If you have set the AutoGenerateColumns
property to true
or not set at all(by default it is true) then no need to loop through your data and bind the gridview. If you want to show the Date
& Description
as separate columns then you can use a markup like this:-
<asp:GridView ID="forecast" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Date" DataField="Date" />
<asp:BoundField HeaderText="Desciption " DataField="Desciption " />
</Columns>
</asp:GridView>
This will display your data without formatting, but if you want some formatting to be done then either do it before assigning the datasource (by storing it in a DataTable or Custom List) or in the RowDataBound
event of gridview.
Upvotes: 1