带有多个下拉列表的Gridview,添加了行&删除asp.net中的按钮

时间:2014-11-13 07:52:25

标签: c# asp.net .net gridview datagridview

我是asp.net的新手,任何人都可以帮助我。 我想在asp.net中创建一个动态网格,它有5个下拉列表绑定数据库 并选择第一个dropdownvalue第二个下拉绑定。它还添加了行&删除 行按钮。

<asp:UpdatePanel runat="server"><ContentTemplate>
<asp:GridView ID="grvparameterdetail" runat="server" 
            ShowFooter="True" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" 
            GridLines="None" OnRowDeleting="grvparameterDetails_RowDeleting" 

    >
<Columns>
    <asp:BoundField DataField="RowNumber" HeaderText="SNo" />
    <asp:TemplateField HeaderText="Company">

        <ItemTemplate>

            <asp:DropDownList DataSource='<%# bindcompany1() %>' DataTextField="Comp_Name" DataValueField="Comp_Code" ID="drpcompany" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpcompany_indexedchanged">

            <asp:ListItem Value="-1">Select</asp:ListItem>

            </asp:DropDownList>

        </ItemTemplate>

    </asp:TemplateField>
    <asp:TemplateField HeaderText="Center">

        <ItemTemplate>

            <asp:DropDownList DataSource='<%# bindunit1() %>' DataTextField="center" DataValueField="Pub_cent_Code" ID="drpcenter" runat="server" AppendDataBoundItems="true">

            <asp:ListItem Value="-1">Select</asp:ListItem>

            </asp:DropDownList>

        </ItemTemplate>

    </asp:TemplateField>
    <asp:TemplateField HeaderText="Publ.Type">

        <ItemTemplate>

            <asp:DropDownList DataSource='<%# bindptype1() %>' DataTextField="pubname" DataValueField="pubtypecode" ID="drppubtype" runat="server" AppendDataBoundItems="true">

            <asp:ListItem Value="-1">Select</asp:ListItem>

            </asp:DropDownList>

        </ItemTemplate>
        </asp:TemplateField>
    <asp:TemplateField HeaderText="Publication">

        <ItemTemplate>

            <asp:DropDownList ID="drppub" runat="server" AppendDataBoundItems="true">

            <asp:ListItem Value="-1">Select</asp:ListItem>

            </asp:DropDownList>

        </ItemTemplate>

        </asp:TemplateField>
    <asp:TemplateField HeaderText="Edition">

        <ItemTemplate>

            <asp:DropDownList ID="drppubed" runat="server" AppendDataBoundItems="true">

            <asp:ListItem Value="-1">Select</asp:ListItem>

            </asp:DropDownList>

        </ItemTemplate>
        <FooterStyle HorizontalAlign="Right" />
        <FooterTemplate>
            <asp:Button ID="ButtonAdd" runat="server" 
                    Text="Add New Row" OnClick="ButtonAdd_Click" />
        </FooterTemplate>
    </asp:TemplateField>
    <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" />

    

aspx.cs代码

if (!Page.IsPostBack)
    {

        FirstGridViewRow();
    }

private void FirstGridViewRow()
{

    DataTable dt = new DataTable();

    DataRow dr = null;
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));
    dt.Columns.Add(new DataColumn("Col4", typeof(string)));
    dt.Columns.Add(new DataColumn("Col5", typeof(string)));
    dr = dt.NewRow();
    dr["RowNumber"] = 1;
    //dr["Col2"] = string.Empty;
    //dr["Col3"] = string.Empty;
    //dr["Col4"] = string.Empty;
    //dr["Col5"] = string.Empty;
    dt.Rows.Add(dr);

    ViewState["CurrentTable"] = dt;

    grvparameterdetail.DataSource = dt;
    grvparameterdetail.DataBind();


}

private void AddNewRow()
{
    int rowIndex = 0;

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            drCurrentRow = dtCurrentTable.NewRow();
            drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;

            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;
            for (int i = 1; i <= dtCurrentTable.Rows.Count - 1; i++)
            {
                DropDownList Drpcompany =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");

                DropDownList drpcenter =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");

                DropDownList drppubtype =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");

                DropDownList Drppublication =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");

                DropDownList Drpedition =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");


                //drCurrentRow = dtCurrentTable.NewRow();
                //drCurrentRow["RowNumber"] = i + 1;

                dtCurrentTable.Rows[i]["Col1"] = Drpcompany.SelectedValue;
                dtCurrentTable.Rows[i]["Col2"] = drpcenter.SelectedValue;
                dtCurrentTable.Rows[i]["Col3"] = drppubtype.SelectedValue;
                dtCurrentTable.Rows[i]["Col4"] = Drppublication.SelectedIndex;
                dtCurrentTable.Rows[i]["Col5"] = Drpedition.SelectedValue;
                rowIndex++;
            }
            //dtCurrentTable.Rows.Add(drCurrentRow);
            //ViewState["CurrentTable"] = dtCurrentTable;

            grvparameterdetail.DataSource = dtCurrentTable;
            grvparameterdetail.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }
    SetPreviousData();
}

private void SetPreviousData()
{
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DropDownList Drpcompany =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");

                DropDownList drpcenter =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");

                DropDownList drppubtype =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");

                DropDownList Drppublication =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");

                DropDownList Drpedition =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");


                Drpcompany.SelectedValue = dt.Rows[i]["Col1"].ToString();
                drpcenter.SelectedValue = dt.Rows[i]["Col2"].ToString();
                drppubtype.SelectedValue = dt.Rows[i]["Col3"].ToString();
                Drppublication.SelectedValue = dt.Rows[i]["Col4"].ToString();
                Drpedition.SelectedValue = dt.Rows[i]["Col5"].ToString();
                rowIndex++;
            }
        }
    }
}

protected void grvparameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    SetRowData();
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        int rowIndex = Convert.ToInt32(e.RowIndex);
        if (dt.Rows.Count > 1)
        {
            dt.Rows.Remove(dt.Rows[rowIndex]);
            drCurrentRow = dt.NewRow();
            ViewState["CurrentTable"] = dt;
            grvparameterdetail.DataSource = dt;
            grvparameterdetail.DataBind();

            for (int i = 0; i < grvparameterdetail.Rows.Count - 1; i++)
            {
                grvparameterdetail.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
            }
            SetPreviousData();
        }
    }
}

private void SetRowData()
{
    int rowIndex = 0;

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                DropDownList Drpcompany =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");

                DropDownList drpcenter =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");

                DropDownList drppubtype =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");

                DropDownList Drppublication =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");

                DropDownList Drpedition =
                  (DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["RowNumber"] = i + 1;
                dtCurrentTable.Rows[i - 1]["Col1"] = Drpcompany.SelectedValue;
                dtCurrentTable.Rows[i - 1]["Col2"] = drpcenter.SelectedValue;
                dtCurrentTable.Rows[i - 1]["Col3"] = drppubtype.SelectedValue;
                dtCurrentTable.Rows[i - 1]["Col4"] = Drppublication.SelectedValue;
                dtCurrentTable.Rows[i - 1]["Col5"] = Drpedition.SelectedValue;
                rowIndex++;
            }

            ViewState["CurrentTable"] = dtCurrentTable;
            //grvStudentDetails.DataSource = dtCurrentTable;
            //grvStudentDetails.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }
    //SetPreviousData();
}

protected void drpcompany_indexedchanged(object sender, EventArgs e)
{
  //what to write here
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

我已经制作了示例代码,很容易了解如何启动任务。     我已经完成了harcoded数据..而不是硬编码使用数据库中的数据..     评论......


第1页:aspx文件

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="jquery.js.js"></script>
        <script type="text/javascript">

        </script>
</head>
<body>
    <form id="form1" runat="server">

        <table>
            <tr>
                <td>Last Name</td>
                <td>
                    <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Speciality</td>
                <td>
                    <asp:DropDownList ID="ddlSpeciality" runat="server">
                        <asp:ListItem Text="" />
                        <asp:ListItem Text="aaa" />
                        <asp:ListItem Text="bbb" />
                        <asp:ListItem Text="ccc" />
                    </asp:DropDownList></td>
            </tr>
            <tr>
                <td>Location</td>
                <td>
                    <asp:DropDownList ID="ddlLocation" runat="server">
                        <asp:ListItem Text="" />
                        <asp:ListItem Text="bangalore" />
                        <asp:ListItem Text="chennai" />
                        <asp:ListItem Text="hyderabad" />
                    </asp:DropDownList></td>
            </tr>
            <tr>

                <td colspan="2" align="center">
                    <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></td>
            </tr>
        </table>


    </form>
</body>
</html>

第1页:cs文件

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
            }

            protected void btnSearch_Click(object sender, EventArgs e)
            {
                string lastName = txtLastName.Text.Trim();
                string speciality = ddlSpeciality.Text;
                string location = ddlLocation.Text;
                Response.Redirect(string.Format("page2.aspx?lastname={0}&speciality={1}&location={2}",lastName ,speciality , location));


            }
        }


    }

第2页:aspx文件

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="page2.aspx.cs" Inherits="WebApplication1.test" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>

                <asp:GridView ID="gvdata" runat="server">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkID"  OnClick="LinkButton1_Click" Text="Details" runat="server"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
    </html>

第2页:cs文件

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication1
    {
        public partial class test : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Page.IsPostBack) { }
                else
                {
                    string lastname = Request.QueryString["lastname"];
                    string speciality = Request.QueryString["speciality"];
                    string location = Request.QueryString["location"];

                    string query = lastname.Length == 0 ? "" : "lastname ='" + lastname + "' and";
                    query += speciality.Length == 0 ? "" : "speciality ='" + speciality + "' and";
                    query += location.Length == 0 ? "" : "location ='" + location + "' ";

                    query = query.Trim().TrimStart(new char[] { 'a', 'n', 'd' }).TrimEnd(new char[] { 'a', 'n', 'd' });

                    query = "select * from tablename where " +( query.Length == 0 ? "1=1" : query);
                    // use this query to get data from sql database
                    // use shld get the data from db
                    // for example, i  have hardcoded the datatable with some  values

                    DataTable dt = new DataTable();
                    dt.Columns.Add("ID", typeof(int));
                    dt.Columns.Add("lastname", typeof(string));
                    dt.Columns.Add("speciality", typeof(string));
                    dt.Columns.Add("location", typeof(string));
                    dt.Rows.Add(1, "karthik", "aaa", "bangalore");
                    dt.Rows.Add(2, "parthip", "aaa", "chennai");
                    dt.Rows.Add(3, "krishna", "aaa", "hyderabad");


                    gvdata.DataSource = dt;
                    gvdata.DataBind();



                }
            }

            protected void LinkButton1_Click(object sender, EventArgs e)
            {
                string id  = ((sender as LinkButton).Parent.Parent as GridViewRow).Cells[1].Text;
                Response.Redirect("page3.aspx?id=" + id);
            }
        }
    }

第3页:aspx文件

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="page3.aspx.cs" Inherits="WebApplication1.page3" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div runat="server" id="divcontent">
            </div>
        </form>
    </body>
    </html>

第3页:cs文件

        using System;
        using System.Collections.Generic;
        using System.Data;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;

         namespace WebApplication1
        {
        public partial class page3 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Page.IsPostBack) { }
                else
                {
                     string id = Request.QueryString["id"];
                    // use this id to fetch the data from db to get the details.

                     // get the data from db..
                    // i have hardcoded
                     DataTable dt = new DataTable();
                     dt.Columns.Add("ID", typeof(int));
                     dt.Columns.Add("lastname", typeof(string));
                     dt.Columns.Add("speciality", typeof(string));
                     dt.Columns.Add("location", typeof(string));
                     dt.Rows.Add(1, "karthik", "aaa", "bangalore");
                     Table tbl = new Table() { CellPadding=1 , CellSpacing=2 , BorderColor = System.Drawing.Color.Red, BorderWidth=1 };

                     foreach (DataColumn col in dt.Columns)
                     {
                         TableRow tr = new TableRow() { BorderWidth=1 , BorderColor = System.Drawing.Color.Red };
                         tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = col.ColumnName});
                         tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = dt.Rows[0][col].ToString()});
                         tbl.Rows.Add(tr);

                        }

                     divcontent.Controls.Add(tbl);
                     }



            }
        }
    }