ASP.NET 2.0 GridVieW中控制一个DropDownList在编辑状态时出现对应值

来源:互联网 发布:java 进度条任务监控 编辑:程序博客网 时间:2024/05/21 13:57

控制DropDownList的值.以下简称为DDL

做了2个例子,在控制GridView中的DDL时,出现了相同问题,但解决时用同一个方法却一个能解决一个不能解决.现在还是没弄清楚为什么会这样.写下来留着以后在解决.

第一个例子!

前代码:

<div id="CityDiv" align="center">
              <b>城  市</b><br /><br />
              <asp:GridView ID="gvCity" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="6" DataKeyNames="City_ID" CellPadding="10" OnPageIndexChanging="gvCity_PageIndexChanging" OnRowDeleting="gvCity_RowDeleting" OnRowEditing="gvCity_RowEditing" OnRowUpdating="gvCity_RowUpdating" OnRowCancelingEdit="gvCity_RowCancelingEdit" OnRowDataBound="gvCity_RowDataBound">
                <Columns>
                    <asp:TemplateField HeaderText="选择">
                        <ItemTemplate>
                            <asp:CheckBox ID="CbCity" runat="server" />
                        </ItemTemplate>
                        <HeaderTemplate>
                            <input id="CheckBoxCity" type="checkbox" onclick="CheckAllCity(this);" runat="server" />全选
                        </HeaderTemplate>
                             <ItemStyle VerticalAlign="Top" HorizontalAlign="Center" />
                            <HeaderStyle HorizontalAlign="Right" Width="73px" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="城市编号">
                        <ItemTemplate>
                            <a title="城市编号" href="GVReturnPage.aspx?id=<%# Eval("City_ID") %>&Type=1">
                            <asp:Label ID="lblCId" runat="server" Text='<%# Eval("City_ID") %>'></asp:Label>
                            </a>
                        </ItemTemplate>
                        <HeaderStyle Font-Underline="True" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="城市名称">
                        <ItemTemplate>
                            <a title="<%# Eval("City_Name") %>" href="GVReturnPage.aspx?id=<%# Eval("City_ID") %>&Type=1">
                            <asp:Label ID="lblCName" runat="server" Text='<%# GetShortName(Eval("City_Name").ToString(),6) %>'></asp:Label>
                            </a>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtCName" runat="server" Text='<%# Bind("City_Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <HeaderStyle Font-Underline="True" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="省份名称" HeaderStyle-Font-Underline="true">
                        <ItemTemplate>
                            <asp:label ID="lblPNameC" runat="Server" Text='<%# Eval("Province_Name") %>'></asp:label>  

                          //HiddenField控件可以不用
                           <asp:HiddenField ID="hfPId" runat="server"  Value='<%# Eval("Province_Id") %>' />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="DDLP" runat="Server" DataSource='<%# BindGvDdl() %>' DataValueField="Province_ID" DataTextField="Province_Name">
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField> 
                    <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
                    <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
                </Columns>
                <RowStyle VerticalAlign="Middle" HorizontalAlign="Center" />
              </asp:GridView>
              <br /><br /><br />
              城市编号:&nbsp;&nbsp;
              <asp:TextBox ID="txtCId" runat="server" Text=""></asp:TextBox><br/>
              城市名称:&nbsp;&nbsp;
              <asp:TextBox ID="txtCN" runat="server" Text=""></asp:TextBox>
              <br />
              省份名称:&nbsp;&nbsp;
              <asp:DropDownList ID="ddlP" runat="server" AutoPostBack="false" Width="155px"><asp:ListItem Selected="True" Value="-------"></asp:ListItem></asp:DropDownList>
              <br /><br />
              <p><asp:Button ID="btnAddC" runat="server" Text="新  增" OnClick="btnAddC_Click" />
              <asp:Button ID="btnClearC" runat="server" Text="清  空" OnClick="btnClearC_Click" /></p>
        </div>

后台代码相关DDL代码:

string lblPName;//存储lblPName的值

    protected void gvCity_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.gvCity.EditIndex = e.NewEditIndex;

        lblPName = ((Label)gvCity.Rows[e.NewEditIndex].Cells[3].FindControl("lblPNameC")).Text;

        BindCityAndDDL(); //绑定了GridView和DDL的一个方法
    }

    protected void gvCity_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) != 0)
            {
                e.Row.Cells[0].BackColor = System.Drawing.Color.Red;//第一列在编辑状态时显示红色

                DropDownList ddl = ((DropDownList)e.Row.Cells[3].FindControl("DDLP"));

                if (ddl != null)
                {

                    //这个方法在这个例子中可以为DDL赋值.首先确定lblPNanme是有值
                    ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(lblPName));
                }
            }
        }
    }

 

第2个例子!

前台代码:

<%@ Page Language="C#" AutoEventWireup="true"  EnableEventValidation="false" CodeFile="OnlyGridView.aspx.cs" Inherits="GridView_OnlyGridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <div><center>
            <asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                PageSize="5" DataKeyNames="L_ID" CellPadding="4" ForeColor="#333333" GridLines="None"
                OnPageIndexChanging="gv_PageIndexChanging" OnRowCancelingEdit="gv_RowCancelingEdit"
                OnRowDeleting="gv_RowDeleting" OnRowEditing="gv_RowEditing" OnRowUpdating="gv_RowUpdating" OnRowDataBound="gv_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="L_ID" HeaderText="ID" ReadOnly="True" />
                    <asp:BoundField DataField="L_Name" HeaderText="Name" />
                    <asp:TemplateField HeaderText="DDL/Name">
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Eval("W_Name") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlName" runat="server" DataSource='<%# BindDdl() %>' DataValueField="W_ID"
                                DataTextField="W_Name" >
                            </asp:DropDownList>

                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
                </Columns>
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#EFF3FB" />
                <EditRowStyle BackColor="#2461BF" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="White" />
            </asp:GridView>
            <p>名称:<asp:TextBox ID="txtAddName" runat="server" Text=""></asp:TextBox></p>
            <p>数量:<asp:DropDownList ID="ddlAddNumber" runat="server" DataSource='<%# BindDdl() %>' DataValueField="W_ID" DataTextField="W_Name"></asp:DropDownList></p>
            <p><asp:Button ID="btnAdd" runat="server" Text="新 增" OnClick="btnAdd_Click" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Button id="btnExcelP" runat="server" Text="打 印" OnClick="btnExcelP_Click" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Button ID="btnClear" runat="server" Text="清 空" OnClick="btnClear_Click" /></p>
            </center>
        </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;

public partial class GridView_OnlyGridView : System.Web.UI.Page
{
    //获取另DDL所要显示的Indext
    string strShow;
    string strName;
    string strNumber;

    //存储新增返回值,true 成功.
    bool insertV;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGv();
            //绑页面上的ddlAddNumber
            DdlSource();
        }
    }

    private SqlConnection Con()
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShangHai"].ToString());
        con.Open();

        return con;
    }
    protected DataTable tableL()
    {
        DataTable dt = new DataTable();

        try
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT L.*,(SELECT W.W_Name FROM LW_TableW W WHERE W.W_ID=L.L_Number ) AS W_Name FROM LW_Table AS L", Con());
            sda.Fill(dt);
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }

        return dt;
    }
    private void BindGv()
    {
        this.gv.DataSource = tableL();
        this.gv.DataBind();
    }
    public DataTable BindDdl()
    {
       
        //SqlCommand com = new SqlCommand("SELECT * FROM LW_TableW", Con());
        //SqlDataReader dr = com.ExecuteReader(CommandBehavior.CloseConnection);
        //return dr;

        SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM LW_TableW", Con());
        DataTable dt = new DataTable();
        sda.Fill(dt);

        return dt;
    }
    public void DdlSource()
    {
        this.ddlAddNumber.DataSource = BindDdl();
        this.ddlAddNumber.DataValueField = "W_ID";
        this.ddlAddNumber.DataTextField = "W_Name";
        this.ddlAddNumber.DataBind();
    }

    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int existId;
        int RowId;
        try
        {
            RowId = (int)gv.DataKeys[e.RowIndex].Value;
            SqlCommand com = new SqlCommand("DELETE FROM LW_Table WHERE L_ID=" + RowId + "", Con());
            existId = com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }

        BindGv();
    }
    protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gv.EditIndex = -1;

        BindGv();
    }
    protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            gv.EditIndex = e.NewEditIndex;

            strShow = ((HiddenField)gv.Rows[e.NewEditIndex].Cells[2].FindControl("hfPiD")).Value.Trim();

            BindGv();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string lName;
        int lNumber;
        int id;
        try
        {
            id = (int)gv.DataKeys[e.RowIndex].Value;
            lName = ((TextBox)gv.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            lNumber = Convert.ToInt32(((DropDownList)gv.Rows[e.RowIndex].Cells[2].FindControl("ddlName")).SelectedValue);

            SqlCommand com = new SqlCommand("UPDATE LW_Table SET L_Name='"+ lName +"',L_Number="+ lNumber +" WHERE L_ID="+ id +" ",Con());
            com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }

        gv.EditIndex = -1;

        BindGv();
    }
    protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;

        BindGv();
    }


    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) != 0)
            {
                e.Row.Cells[0].BackColor = System.Drawing.Color.Red;//处在编辑状态的行的第一列背景色是红色

                DropDownList ddlW = (DropDownList)e.Row.FindControl("ddlName");
                if (ddlW != null)
                {

                    //可用
                    ddlW.Text = strShow;

                    //例子1中的下面同样方法在这里用就没反应,通过断点跟踪,发现根本找不到对应的ListItem,

                   //但strShow有值.很不明白为什么会这样?

                     ddlW.SelectedIndex = ddlW.Items.IndexOf(ddlW.Items.FindByText(strShow));

                    ;//此方法只能在DDL本身的Index与数据库里的自增自段ID按0和1,1和2,2和3这样对应才能用:
                    //一但对应错开,那下面写发就会报错,DDL超出索引界限
                    //ddlW.Items[Convert.ToInt32(strShow)-1].Selected = true               

              }
                else
                {
                    Response.Write("没找到DDL");
                }
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        strName = this.txtAddName.Text.Trim();

        if (strName != string.Empty)
        {
            strNumber = ddlAddNumber.SelectedValue.Trim();

            if (OnlyName(strName))
            {
                insertV =  AddOneRow(strName ,Convert.ToInt32(strNumber));

                if (insertV)
                {
                    Response.Write("<scipt>alert('新增成功!')</script>");
                }
                else
                {
                    Response.Write("<scipt>alert('新增失败!')</script>");
                }
            }
        }

        BindGv();
    }

    //新增数据
    private bool AddOneRow(string name,int number)
    {
        int AddCount;
        string strSql = "INSERT INTO LW_Table VALUES('"+ name +"',"+ number +")";

        SqlCommand com = new SqlCommand(strSql, Con());
        AddCount = com.ExecuteNonQuery();

        if (AddCount == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //根据Name判断唯一
    private bool OnlyName(string name)
    {
        int rowCount;

        string strSql = "SELECT Count(*) FROM  LW_Table WHERE L_Name='"+ name +"'";

        SqlCommand com = new SqlCommand(strSql,Con());
        rowCount = (int)com.ExecuteScalar();

        if (rowCount != 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        this.txtAddName.Text = "";
    }
    protected void btnExcelP_Click(object sender, EventArgs e)
    {
        PrintExcel();
    }

    #region 打印Excel详细方法
    private void PrintExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.ContentEncoding = Encoding.UTF7;
        Response.AddHeader("Content-Disposition", "attachent;filename=TestExcel.xls");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/ms.excel";
        System.IO.StringWriter stringW = new System.IO.StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(stringW);

        this.gv.AllowPaging = false;
        this.gv.HeaderStyle.BackColor = System.Drawing.Color.White;
        this.gv.HeaderStyle.ForeColor = System.Drawing.Color.Black;
        this.gv.Columns[3].Visible = false;
        this.gv.Columns[4].Visible = false;
        BindGv();

        this.gv.RenderControl(htw);

        Response.Write(stringW.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    #endregion

例子2中还有打印成EXCEL功能