获取foreach项目以在网格c#asp.net中显示

时间:2015-04-07 12:22:00

标签: c# asp.net web-services gridview foreach

我正在使用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 + "|";
            }

2 个答案:

答案 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属性设置为DateDescription(或将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();
}