GridView奇怪的行为

时间:2010-10-29 21:32:50

标签: asp.net

我在页面上有问题,在gdvCar_DataBound我添加了三个按钮,当我点击其中任何一个时,页面转到回发但没有输入gdvCar_RowCommand然后那些按钮(以及我在gdvCar_DataBound中添加的图像) disaper。然后网格就像gdvCar_DataBound不执行一样。我的问题是为什么它没有进入gdvCar_RowCommand?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HMS.library;
using System.Data.SqlClient;

namespace HMS
{
    public partial class Cars : System.Web.UI.Page
    {
        #region fields
        private const Int16 PageId = 1;
        private String connectionString = "Server=localhost;Database=hms_test;Trusted_Connection=True;";
        String[] filters = null;
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                FillProducer();
                FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
                RestoreFilters();
                FillGrid();


            }


        }


        #region events
        protected void ddlProducer_Changed(object sender, EventArgs e)
        {
            if (ddlProducer.SelectedValue != "0")
            {
                ddlModel.Enabled = true;
                FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
            }
            else
            {
                ddlModel.SelectedValue = "0";
                ddlModel.Enabled = false;
            }
            upSearch.Update();
        }

        protected void gdvCar_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Reserve":
                    {
                        pnlReserve.Visible = true;
                        break;
                    }
                case "Phone":
                    {
                        break;
                    }
                case "Email":
                    {
                        break;
                    }

            }

        }

        protected void gdvCar_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                String id = e.Row.Cells[0].Text;
                Image img = new Image();
                img.ID = "img_one" + id;
                img.Width = 96;
                img.Height = 96;
                img.ImageUrl = "images/car/" + e.Row.Cells[7].Text;
                e.Row.Cells[7].Controls.Add(img);
                img = new Image();
                img.ID = "img_two" + id;
                img.Width = 96;
                img.Height = 96;
                img.ImageUrl = "images/car/" + e.Row.Cells[8].Text;
                e.Row.Cells[8].Controls.Add(img);
                img = new Image();
                img.ID = "img_three" + id;
                img.Width = 96;
                img.Height = 96;
                img.ImageUrl = "images/car/" + e.Row.Cells[9].Text;
                e.Row.Cells[9].Controls.Add(img);


                ImageButton imbReserve = new ImageButton();
                imbReserve.ID = "res" + id;
                imbReserve.Enabled = true;
                imbReserve.Width = 48; imbReserve.Height = 48;
                imbReserve.ToolTip = "Reserve"; imbReserve.AlternateText = "Reserve";
                imbReserve.ImageUrl = "images/icons/key.gif";
                imbReserve.CommandName = "Reserve";
                imbReserve.CommandArgument = id;
                e.Row.Cells[10].Controls.Add(imbReserve);


                ImageButton imbPhone = new ImageButton();
                imbPhone.ID = "phone" + id;
                imbPhone.Enabled = true;
                imbPhone.Width = 48; imbPhone.Height = 48;
                imbPhone.ToolTip = "Reserve by phone"; imbPhone.AlternateText = "Phone";
                imbPhone.ImageUrl = "images/icons/phone.jpg";
                imbPhone.CommandName = "Phone";
                imbPhone.CommandArgument = id;
                e.Row.Cells[11].Controls.Add(imbPhone);

                ImageButton imbEmail = new ImageButton();
                imbEmail.ID = "email" + id;
                imbEmail.Enabled = true;
                imbEmail.Width = 48; imbEmail.Height = 48;
                imbEmail.ToolTip = "Reserve by email"; imbEmail.AlternateText = "Email";
                imbEmail.ImageUrl = "images/icons/email.jpg";
                imbEmail.CommandName = "Email";
                imbEmail.CommandArgument = id;
                e.Row.Cells[12].Controls.Add(imbEmail);





            }
        }

        protected void imbSearch_Click(object sender, ImageClickEventArgs e)
        {
            StoreFilters();
            FillGrid();

        }
        #endregion

        #region functions
        private void FillProducer()
        {
            hmsDataContext hms = new hmsDataContext();
            var source = from o in hms.producer_cars
                         orderby o.name
                         select new
                         {
                             o.id,
                             o.name
                         };
            foreach (var temp in source)
                ddlProducer.Items.Add(new ListItem(temp.name, temp.id.ToString()));
            ddlProducer.Items.Insert(0, (new ListItem("all producers", "0")));
        }

        private void FillModel(int producer_id)
        {
            hmsDataContext hms = new hmsDataContext();
            var source = from o in hms.model_cars
                         from p in hms.producer_cars
                         where o.producer_car_id == producer_id && p.id == producer_id
                         orderby o.name
                         select new
                         {
                             o.id,
                             o.name
                         };
            ddlModel.Items.Clear();
            foreach (var temp in source)
                ddlModel.Items.Add(new ListItem(temp.name, temp.id.ToString()));
            ddlModel.Items.Insert(0, (new ListItem("all producers", "0")));
        }

        private void FillGrid()
        {
            SqlConnection conn = new SqlConnection(connectionString);
            String command = @"SELECT car.id AS id, car.price as price, car.weight as weight,
car.year as year, producer_car.name as producer, model_car.name as model, car.number_seats as number_seats, car.photo_one as photo_one,car.photo_two as photo_two,car.photo_three as photo_three, '' as reserver,'' as phone,'' as email
FROM car INNER JOIN model_car on car.model_car_id=model_car.id
INNER JOIN producer_car on model_car.producer_car_id=producer_car.id";
            if(filters!=null){
                String[] search=new String[5];

                search[0]=filters[0]!="0"?"producer_car.id="+filters[0]:"";
                search[1]= filters[1] != "0" ? "model_car.id=" + filters[1] : "";
                search[2]=filters[2]!=""?"car.color LIKE \'"+filters[2]+"\'":"";
                search[3]=filters[3]!=""?"car.price<"+filters[3]:"";
                search[4] = filters[4] != "" ? "car.number_seats=" + filters[4] : "";
                var a=from f in search
                      where f!=""
                      select f;
                String filterAddition="";

                if(a.Count()>0){
                    filterAddition=" WHERE ";
                    foreach ( var b in a){
                        filterAddition+=" "+b+" AND";
                    }
                    filterAddition=filterAddition.EndsWith("AND")?filterAddition.Substring(0,filterAddition.Length-3):filterAddition;

                }

               command+=filterAddition;

            }
            SqlCommand comm = new SqlCommand(command, conn);
            SqlDataReader r = null; 
            try
            {
                comm.Connection.Open();
                r =comm.ExecuteReader();
                gdvCar.DataSource = r;
                gdvCar.DataBind();
                r.Close();
            }
            catch (Exception exc)
            {
                throw (exc);
            }
            finally
            {


                conn.Close();
            }

        }

        private void StoreFilters()
        {
            filters = new String[5];
            filters[0] = ddlProducer.SelectedValue;
            filters[1] = ddlModel.SelectedValue;
            filters[2] = ddlColor.SelectedValue;
            filters[3] = txtStartPrice.Text;

            filters[4] = ddlNumber.SelectedValue;
            Session["1"] = filters;
        }

        private void RestoreFilters()
        {
            if (Session["1"] != null)
            {
                filters = (String[])Session["1"];
                ddlProducer.SelectedValue = filters[0];
                ddlProducer_Changed(null, null);
                ddlModel.SelectedValue = filters[1];
                ddlColor.SelectedValue = filters[2];
                txtStartPrice.Text = filters[3];

                ddlNumber.SelectedValue = filters[4];
            }

        }

        private void ReserveCar(String FirstName, String LastName, DateTime Start, DateTime End, String Visa, Int16 CarId)
        {
            hmsDataContext hms = new hmsDataContext();
            var a = from c in hms.cars
                    from rc in hms.rented_cars
                    where c.id == rc.id_car && c.id == CarId
                    select new
                    {
                        start = rc.start,
                        end = rc.end
                    };

            Boolean free = false;
            if (a.Count() == 0)
            {
                free = true;
            }
            else if (a.Count() == 1)
            {
                if ((a.First().start > End) || (a.First().end < Start))
                    free = true;
            }
            else
            {
                if ((a.First().start > End) || (a.First().end < Start))
                    free = true;
                else if(!free)
                {
                    int n = a.Count();
                    for (int i = 0; (i < n - 1) && (!free); i++)
                    {
                        if (a.ElementAt(i).end < Start && a.ElementAt(i + 1).start > End)
                            free = true;
                        i++;
                    }
                    if (!free)
                    {
                        if (a.ElementAt(n - 1).end < Start)
                            free = true;
                    }
                }
            }

            if (free)
            {
                //insert
            }
            else
            {
                //label-nije slobodno za taj termin
            }
        }

        #endregion


    }
}

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Cars.aspx.cs" Inherits="HMS.Cars"
    MasterPageFile="~/frame.Master" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:Content ContentPlaceHolderID="content" ID="con" runat="server">
    <link rel="StyleSheet" href="css/menu.css" type="text/css" media="all">
    <asp:ScriptManager ID="sc" runat="server">
    </asp:ScriptManager>
    <div id="menu">
        <ul class="glossymenu">
            <li><a href="Home.aspx"><b>Home</b></a></li>
            <li class="current"><a href="Cars.aspx"><b>Cars</b></a></li>
            <li><a href="Boats.aspx"><b>Boats</b></a></li>
            <li><a href="Contact.aspx"><b>Contact</b></a></li>
            <li><a href="Admin.aspx"><b>Admin</b></a></li>
        </ul>
    </div>
    <div>
        <div>
            <asp:UpdatePanel ID="upSearch" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <div id="search">
                        <fieldset>
                            <legend>Advanced search</legend>
                            <table>
                                <tr>
                                    <td>
                                        Proizvođač:<asp:DropDownList ID="ddlProducer" runat="server" OnSelectedIndexChanged="ddlProducer_Changed"
                                            AutoPostBack="true">
                                        </asp:DropDownList>
                                    </td>
                                    <td>
                                        Model:<asp:DropDownList ID="ddlModel" runat="server" Enabled="false">
                                        </asp:DropDownList>
                                    </td>
                                    <td>
                                        Boja:<asp:DropDownList ID="ddlColor" runat="server">
                                            <asp:ListItem Text="all" Value=""></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                            <asp:ListItem Text="White" Value="white"></asp:ListItem>
                                            <asp:ListItem Text="Green" Value="green"></asp:ListItem>
                                        </asp:DropDownList>
                                    </td>
                                    <td>
                                        Cena do:
                                        <asp:TextBox ID="txtStartPrice" runat="server" MaxLength="10"></asp:TextBox>
                                        din/dan
                                    </td>
                                    <td>
                                        Number seats:<asp:DropDownList ID="ddlNumber" runat="server">
                                            <asp:ListItem Text="-- --" Value=""></asp:ListItem>
                                            <asp:ListItem Text="1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="4" Value="4"></asp:ListItem>
                                            <asp:ListItem Text="5" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="6" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="7" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="8" Value="4"></asp:ListItem>
                                            <asp:ListItem Text="9" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="10" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="11" Value="4"></asp:ListItem>
                                        </asp:DropDownList>
                                    </td>
                                    <td>
                                        <asp:ImageButton ID="imbSearch" runat="server" ImageUrl="images/icons/search.png"
                                            Width="32" Height="32" ToolTip="Search by choosen criterions" AlternateText="Search"
                                            OnClick="imbSearch_Click" />
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </div>

                </ContentTemplate>
            </asp:UpdatePanel>
            <br />
            <br />
            <div>
                <asp:UpdatePanel ID="upGrid" runat="server" UpdateMode="Always">
                    <ContentTemplate>
                        <asp:GridView ID="gdvCar" runat="server"  OnRowCommand="gdvCar_RowCommand"
                            OnRowDataBound="gdvCar_DataBound">
                        </asp:GridView>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
            <div>
            <asp:UpdatePanel ID="upTemp" runat="server"><ContentTemplate>
                <asp:Panel ID="pnlReserve" runat="server" Visible="false" Width="400" Height="400">
                <asp:UpdatePanel ID="upReserve" runat="server">
                <ContentTemplate>

                </ContentTemplate>
                </asp:UpdatePanel>
                </asp:Panel>
                </ContentTemplate></asp:UpdatePanel>
            </div>

        </div>
</asp:Content>

2 个答案:

答案 0 :(得分:0)

您必须在每个Postback上重新创建RowCreated中的按钮,否则它们的事件将不会触发。

在ViewState中保存RowDataBound所需的内容。在RowCreated中,基于Viewstate值在Postback上重新创建它们(RowDatabound只在Databinding上调用)。然后,所有控件都可以在page-lifecyle早期提供,以提升他们的活动。

答案 1 :(得分:0)

我相信你可以用更优雅的方式做到,看一看,

<asp:GridView ...>
<Columns>
<asp:BoundField HeaderText="Some Caption" DataField="Column name from the DataReader result"/>
...
<asp:TemplateField HeaderText="Image..">
<asp:Image runat="server" ImageUrl='<%# String.Format("images/car/{0}", Eval("The column name from the DataReader of the cell 7") %>' />
</asp:TemplateField>

<asp:TemplateField HeaderText="ImageButton..">
<asp:ImageButton runat="server" .../>
</asp:TemplateField>
</Columns>
</asp:GridView>

然后您不必在代码中添加按钮和图像,并且每次创建行时都要添加它们,您只需要从数据库中获取数据并设置gridview的DataSource,并且我想你也可以摆脱获取数据的代码并用SqlDataSource替换它。

看看这篇关于GridView的文章, http://msdn.microsoft.com/en-us/library/aa479353.aspx

相关问题