通过代码更新GridView中的项目 [英] Updating Items in GridView through Code

查看:113
本文介绍了通过代码更新GridView中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GV,我想更新我的物品。我没有使用LDS或任何因为我更新存储在多个数据库中的项目。

I have a GV in which I want to Update my items. I am not using LDS or anything coz I m updating items which are stored in multiple databases.

以下是我的GV的标记:

Here is the markup of my GV:

<asp:GridView runat="server" Height="233px" Width="602px" ID ="gvShowComm" 
        CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing = "gvShowComm_RowEditing" 
        OnRowUpdating = "gvShowComm_RowUpdating" 
        OnRowCancelingEdit = "gvShowComm_RowCancelingEdit">

    <Columns>
        <asp:CommandField ShowCancelButton="True" ShowEditButton="True" />

     <asp:TemplateField HeaderText = "Product ID">
         <EditItemTemplate>
         <asp:TextBox ID = "ProductName" runat = "server" Text ='<%# Bind("Product_ID") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "ProductName" runat = "server" Text ='<%# Bind("Product_ID") %>'/>
         </ItemTemplate>
     </asp:TemplateField>


     <asp:TemplateField HeaderText = "Plan Name">
         <EditItemTemplate>
         <asp:TextBox ID = "PlanName" runat = "server" Text ='<%# Bind("PlanName") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "PlanName" runat = "server" Text ='<%# Bind("PlanName") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText = "1st Yr Comm">
         <EditItemTemplate>
         <asp:TextBox ID = "HiComm" runat = "server" Text ='<%# Bind("HiCommissionOld") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "HiComm" runat = "server" Text ='<%# Bind("HiCommissionOld") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText = "2nd Yr Comm">
         <EditItemTemplate>
         <asp:TextBox ID = "LowComm" runat = "server" Text ='<%# Bind("LowCommissionOld") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "LowComm" runat = "server" Text ='<%# Bind("LowCommissionOld") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
</asp:GridView>

这里是我一直在尝试的代码,但我无法获取更新后的TEXT, '

And here is code I've been trying but I cant able to get the updated TEXT in my 's' variable:

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["EntitySelected"] == null)
        {
            MessageBox.Show("Please Select an Entity first!");
            Response.Redirect("~/FrontEnd/AgentList.aspx");
        }

        int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
        this.Label3.Text = "You Selected Entity: " + (string)Session["EntitySelected"];

        dbWebEnrollDataContext dt1 = new dbWebEnrollDataContext(); //This has PlanName!
        CommissionsV2DataContext cv1 = new CommissionsV2DataContext(); //Entity_Product_Point
        var td = from s in GetEntity()
                 join r in GetPlanName() on s.Product_ID equals r.Product_ID
                 where s.Entity_ID == getEntity
                 select new
                 {
                     s.Product_ID,
                     r.PlanName,
                     s.HiCommissionOld,
                     s.LowCommissionOld


                 };
        gvShowComm.DataSource = td;
        gvShowComm.DataBind();
    }

    static IEnumerable<Entity_Product_Point> GetEntity()
    {
        var context = new CommissionsV2DataContext();
        return (from t in context.Entity_Product_Points select t).AsQueryable();
    }

    static IEnumerable<PlanMaster> GetPlanName()
    {
        var context = new dbWebEnrollDataContext();
        return (from t in context.PlanMasters select t).AsQueryable();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {


            if (ddlPlan.SelectedValue != null && tb1stYr.Text != "" && tbMaximum.Text != "" && tbRecurring.Text != "")
            {
                //Accessing Variables and defining them.
                using (dbWebEnrollDataContext dt = new dbWebEnrollDataContext())
                    try
                    {
                        int getEntity = Int16.Parse(Session["EntitySelected"].ToString());

                        var productName = ddlPlan.SelectedValue.ToString();

                        decimal firststYrComp = Int16.Parse(tb1stYr.Text.ToString());
                        decimal recurringComp = Int16.Parse(tbRecurring.Text.ToString());
                        decimal maximumPercent = Int16.Parse(tbMaximum.Text.ToString());

                        //Pulling the Product_ID from the PlanMaster Table from WebEnroll DB!

                        //var tr = dt.PlanMasters.First(s => s.PlanName == productName);

                        var tr = from s in dt.PlanMasters
                                 where s.PlanName == productName
                                 select s.Product_ID;

                        decimal finalFirstYrComp = decimal.Round((firststYrComp / maximumPercent), 3);
                        decimal finalRecurringComp = decimal.Round((recurringComp / maximumPercent), 3);

                        //Updating the Table: Entity_Product_Points in CommissionsV2 DB.
                        CommissionsV2DataContext cv = new CommissionsV2DataContext();
                        Entity_Product_Point ev = new Entity_Product_Point();
                        ev.Entity_ID = getEntity;
                        ev.Product_ID = tr.First();
                        ev.HiCommissionOld = (double)firststYrComp;
                        ev.LowCommissionOld = (double)recurringComp;
                        ev.HiCommission = (double)finalFirstYrComp * 100;
                        ev.LowCommission = (double)finalRecurringComp * 100;
                        ev.DateCreated = System.DateTime.Now;
                        cv.Entity_Product_Points.InsertOnSubmit(ev);
                        cv.SubmitChanges();

                        var td = from s in GetEntity()
                                 join r in GetPlanName() on s.Product_ID equals r.Product_ID
                                 where s.Entity_ID == getEntity
                                 select new
                                 {
                                     s.Product_ID,
                                     r.PlanName,
                                     s.HiCommissionOld,
                                     s.LowCommissionOld


                                 };

                        gvShowComm.DataSource = td;
                        gvShowComm.DataBind();

                    }

                    catch (Exception err)
                    {
                        MessageBox.Show("" + err);
                    }
            }

            else
            {
                MessageBox.Show("Please Enter Entry for the textboxes!");
            }

            tb1stYr.Text = "";
            tbMaximum.Text = "";
            tbRecurring.Text = "";
            ddlPlan.SelectedIndex = 0;
        }


    protected void gvShowComm_RowEditing(object sender, GridViewEditEventArgs e) 
    {
        gvShowComm.EditIndex = e.NewEditIndex;
        gvShowComm.DataBind();

    }

    protected void gvShowComm_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvShowComm.EditIndex = -1;
        gvShowComm.DataBind();
    }

    protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        System.Web.UI.WebControls.TextBox myBox = gvShowComm.Rows[e.RowIndex].FindControl("PlanName") as System.Web.UI.WebControls.TextBox;
        string s = myBox.Text;
        gvShowComm.DataBind();
    }



    }


推荐答案

两个想法:
首先,您可以使用模板字段为您的专栏&命名控制
保存您的数据。这些控件的内容可以按如下方式检索:((TextBox)e.Row.FindControl(TextBoxProductName))。Text

模板看起来像这样:

The template would look something like this:

    <asp:TemplateField HeaderText="Product Name">
        <EditItemTemplate>
            <asp:TextBox ID="TextBoxProductName" runat="server" Text='<%# Bind("Product_Name") %>'/>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="LabelProductName" runat="server" Text='<%# Bind("Product_Name") %>'/>
        </ItemTemplate>
    </asp:TemplateField>

请注意,因为您手动绑定了数据绑定的GridView,因此在RowEditing(Not RowUpdating)通过编辑按钮,你必须设置gridview的编辑索引。试试:

Note also that because you are databinding the gridview manually, in the RowEditing (Not the RowUpdating) event fired by the edit button, you must set the gridview's edit index. Try:

gvShowComm.EditIndex = e.Row.RowIndex;

或者,第二,您可以在
gridview中拥有多个数据键。尝试如下所示:
DataKeyNames =Product_ID,Product_Name,Product_Price

Or, second, you can have more than one datakey in a gridview. Try something like: DataKeyNames="Product_ID,Product_Name,Product_Price"

检索如下:

Those values can then be retrieved as follows:

gvShowComm.DataKeys[e.RowIndex]["Product_Name"]

我应该注意到DataKeys只能用于保存数据库主键。将它们用于其他任何事情都是黑客。也就是说,当我需要为每行存储一些信息时,偶尔需要它,但我不希望它对用户可见。

I should note that DataKeys are only really designed to hold db primary keys. Using them for anything else is a hack. That said, I've had need for it occasionally when I need to store some piece of information for each row, but I don't want it visible to the user.

最后一点,不要将数据绑定放在页面加载中,除非您将它放入一个条件中,该条件仅在初始页面加载时触发,而不是每次回发。例如:if(!IsPostback)...

A final note, don't put the databinding in the page load unless you are putting it inside a conditional that only fires on initial page load, not every postback. Ex: if(!IsPostback) ...

这篇关于通过代码更新GridView中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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