模板化的Asp.net Gridview无法正常工作 [英] Templated Asp.net Gridview doesnot work properly

查看:69
本文介绍了模板化的Asp.net Gridview无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好专家,
我通过以下代码创建了一个自定义Asp.net Gridview:

Hello Experts,
I Created a Custom Asp.net Gridview by following code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

            CellPadding="4" ForeColor="#333333" GridLines="None"

                    onrowdeleting="GridView1_RowDeleting"

                    onrowdatabound="GridView1_RowDataBound" ondatabound="GridView1_DataBound"

                    onload="GridView1_Load" onrowcreated="GridView1_RowCreated"

                    ShowFooter="True">
                    <RowStyle BackColor="#EFF3FB" />
                    <Columns>
                        <asp:TemplateField HeaderText="SL">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("RowNumber") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("RowNumber") %>'></asp:TextBox>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Material">
                            <ItemTemplate>
                                <asp:DropDownList ID="drpMaterial" runat="server">
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Quantity">
                            <FooterTemplate>
                                <asp:Label ID="lblTotal" runat="server"></asp:Label>
                            </FooterTemplate>
                            <ItemTemplate>
                                <asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="True"

                                    ontextchanged="txtQuantity_TextChanged">0.00</asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                                    ControlToValidate="txtQuantity" ErrorMessage="Required Field Missing">*</asp:RequiredFieldValidator>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Description">
                            <ItemTemplate>
                                <asp:TextBox ID="txtDescription" runat="server"

                                    ontextchanged="txtDescription_TextChanged1"></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Command">
                            <ItemTemplate>
                                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Add" />
                                <asp:Button ID="Button4" runat="server" Text="Delete" onclick="Button4_Click"

                                    CausesValidation="False" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <EmptyDataTemplate>
                        <asp:Button ID="Button1" runat="server" Text="btnAddNew" />
                        <asp:Button ID="Button2" runat="server" Text="btnDelete" />
                    </EmptyDataTemplate>
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>



和以下c#代码用于操作网格



and Used following c# code for operate the grid

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindwithgrid();
           
        }
       
    }
    dalMaterial dal = new dalMaterial();
    entMaterial ent = new entMaterial();
    private void bindwithgrid()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = ""; 
        dr["Column2"] = "";
        dr["Column3"] = "";
       
        dt.Rows.Add(dr);
        ViewState["CurrentTable"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
    protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            Button lb = (Button)e.Row.FindControl("Button4");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = true;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }
    }
    private void AddNewRowToGrid()
    {

    int rowIndex = 0;   
  
    if (ViewState["CurrentTable"] != null)   
    {   
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];   
       DataRow drCurrentRow = null;   
  
        if (dtCurrentTable.Rows.Count > 0)   
        {   
            foreach (DataRow row in dtCurrentTable.Rows)   
           {   
                foreach (GridViewRow grow in GridView1.Rows)   
               {   
                    if (rowIndex == grow.RowIndex + 1)   
                    {   
                      row["Column2"] = ((TextBox)grow.FindControl("txtQuantity")).Text;   
                      row["Column3"] = ((TextBox)grow.FindControl("txtDescription")).Text;   
                    }   
                }   

                DropDownList Material = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("drpMaterial");   
                TextBox Quantity = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");   
                TextBox Description = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDescription");   
  
                drCurrentRow = dtCurrentTable.NewRow();   
                drCurrentRow["RowNumber"] = rowIndex + 2;   
                if (Material != null)   
               {   
                 drCurrentRow["Column1"] = Material.SelectedValue;   
               }   
               drCurrentRow["Column2"] = Quantity.Text;   
               drCurrentRow["Column3"] = Description.Text;   
 
              rowIndex++;   
           }   
           dtCurrentTable.Rows.Add(drCurrentRow);   
 
           ViewState["CurrentTable"] = dtCurrentTable;   
  
            GridView1.DataSource = dtCurrentTable;   
            GridView1.DataBind();   

            SetPreviousData();   
        }   
    }   
   else  
    {   
       Response.Write("ViewState is null");   
    }   
  
    Response.Write(Session["i"]);   
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
     
        AddNewRowToGrid();
        Calculation();
       
    }
    private void SetPreviousData()
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
           
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    DropDownList Material = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("drpMaterial");
                    TextBox Quantity = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
                    TextBox Description = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDescription");
                    Material.SelectedValue = dt.Rows[i]["Column1"].ToString();
                    Quantity.Text = dt.Rows[i]["Column2"].ToString();
                    Description.Text = dt.Rows[i]["Column3"].ToString();
                    rowIndex++;
                }

            }

        }
    }
    protected void Button4_Click(object sender, EventArgs e)
    {

       Button lb = (Button)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
        int rowID = gvRow.RowIndex+1;

        if (ViewState["CurrentTable"] != null)
        {

            
            DataTable dt = new DataTable(); 
                dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    int i = dt.Rows.Count;
                    dt.Rows.RemoveAt(rowID);
                }
            }
            if (dt.Rows.Count > 0)
            {
                int i = dt.Rows.Count;
            }
            ViewState["CurrentTable"] = dt;

         
            GridView1.DataSource = dt.DefaultView;
            GridView1.DataBind();
            SetPreviousData();
      Calculation();
          }
    }
  
    double total;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList Material = ((DropDownList)e.Row.FindControl("drpMaterial"));
            Material.DataSource = dal.SelectAll().Tables[0].DefaultView;
            Material.DataValueField = "id";
            Material.DataTextField = "name";
            Material.DataBind();
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblTotalPrice = (Label)e.Row.FindControl("lblTotal");

            lblTotalPrice.Text = total.ToString("N2");
        } 
    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
      
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
     
    }
    protected void GridView1_Load(object sender, EventArgs e)
    {
    }
    private void Calculation()
    {
       
        double total = 0.0;
    
        GridViewRow footerRow = GridView1.FooterRow;
        foreach (GridViewRow row in GridView1.Rows)
        {
            TextBox Quantity = ((TextBox)row.FindControl("txtQuantity"));

            total += double.Parse(Quantity.Text);
           
        }
        Label Total = ((Label)footerRow.FindControl("lblTotal"));
        Total.Text = total.ToString("N2");
         
    }
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        
        Calculation();
        foreach (GridViewRow row in GridView1.Rows)
        {
            TextBox Description = ((TextBox)row.FindControl("txtDescription"));

            Description.Focus();

        }
    }

}



我的问题是:
-当我删除任何行时,Gridview也会丢失最后一行的所有值.

-另一个问题无法删除最后一行.


请帮助我解决上述问题

在此先感谢
Mojam



My Problem is :
- When I delete Any row The Gridview also lost All the values of Last row.

- Another Problem Last Row Cannot be Delete.


Please help me to solve above problems

Thanks in advance
Mojam

推荐答案

这里有大量代码需要遍历,没有一个很好的编写或格式化.

删除按钮(愚蠢地)称为Button2.但是删除行的事件称为Button4_Click.第一步是编写可读代码.第二步是使用调试器尝试找出问题所在.

您的文本不是说删除",而是说"btnDelete"?你到底在做什么?

在ASP.NET上购买一本基础书籍,它将解释当您以正确的方式添加删除按钮时传递的事件args,以及如何获取单击该按钮的行的正确索引.在此代码上运行调试器时,其余问题对您来说应该是很清楚的.将来,请阅读如何正确做事,不要盲目猜测.仅仅是因为它可以编译,并不意味着它将按照您的期望进行操作,而是按照您的要求进行操作.
There is a ton of code to wade through here, none of it well written or formatted.

The delete button is (stupidly) called Button2. But the event that deletes a row is called Button4_Click. Your first step is to write readable code. Your second is to use your debugger to try to work out what is going wrong.

Your text, instead of saying ''Delete'', says ''btnDelete'' ? What on earth are you doing here ?

Buy a basic book on ASP.NET, it will explain the event args passed when you add a delete button the proper way, and how you can get the correct index of the row you clicked the button on. The rest of your issues should be perfectly clear to you when you run a debugger on this code. In future, read on how to do things properly, don''t guess blindly. Just because it compiles, does not mean it will do what you hope, it will do what you asked it to.


这篇关于模板化的Asp.net Gridview无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆