我正在使用Weather WebService,我有一个标识forecast
的网格视图。如何在gridview中显示foreach项?我尝试过使用
forecast += item.Date.ToShortDateString() + " " + item.Desciption + "|";
但是我收到了错误
' System.Web.UI.WebControls.GridView'不包含'预测'的定义没有扩展方法'预测'接受第一个 类型' System.Web.UI.WebControls.GridView'的参数可以找到 (您是否缺少using指令或程序集引用?)
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 + "|";
}
答案 0 :(得分:1)
如果您已将AutoGenerateColumns
属性设置为true
或根本未设置(默认情况下为真),则无需循环访问数据并绑定gridview。如果您想显示Date
& Description
作为单独的列,然后您可以使用这样的标记: -
<asp:GridView ID="forecast" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Date" DataField="Date" />
<asp:BoundField HeaderText="Desciption " DataField="Desciption " />
</Columns>
</asp:GridView>
这将显示您的数据而不进行格式化,但是如果您想要进行某些格式化,那么在分配数据源之前(通过将其存储在DataTable或自定义列表中)或在gridview的RowDataBound
事件中执行此操作
答案 1 :(得分:1)
使用以下代码。 ForecastItem
类应该在单独的文件中定义。并向gridview添加两列,将DataField
属性设置为Date
和Description
(或将AutoGenerateColumns
设置为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();
}