ASP.NET - работа с GridView программно - PullRequest
1 голос
/ 19 августа 2009

Я продолжаю с этот пост .

После долгих поисков я придумал этот код для программного редактирования ячеек:

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 Ice_Web_Portal.BO;

namespace GridView___Test
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = Course.GetCourses();
            GridView1.DataBind();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewRow row = GridView1.Rows[e.NewEditIndex];

            GridView1.EditIndex = e.NewEditIndex;

            GridView1.DataSource = Course.GetCourses();
            GridView1.DataBind();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
            TextBox txtCourseCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
            TextBox txtCourseName = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
            TextBox txtCourseTextBookCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];

            Course item = new Course();
            item.ID = Convert.ToInt32(txtID.Text);
            item.CourseCode = txtCourseCode.Text;
            item.CourseName = txtCourseName.Text;
            item.TextBookCode = txtCourseTextBookCode.Text;

            bool success = Course.Update(item);

            labMessage.Text = success.ToString();

            GridView1.EditIndex = -1;
            GridView1.DataSource = Course.GetCourses();
            GridView1.DataBind();
        }
    }
}

Но возникают 2 проблемы.

(1) Мне нужно дважды нажать командные кнопки для редактирования / обновления.

(2) Изменения значений ячеек в базе данных не обновляются. То есть отредактированные значения ячеек не фиксируются.

Может кто-нибудь дать мне решение?

ОБНОВЛЕНИЕ: Мое решение было таким:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridView___Test._Default" %>

<!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>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" Font-Names="Verdana" Font-Size="Small" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">            
        </asp:GridView>

    </div>
    </form>
</body>

</html>

namespace GridView___Test
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!Page.IsPostBack)
            {
                CreateGridView();
            }
        }

        private void CreateGridView()
        {
            GridView1.Columns.Clear();

            DataTable dataTable = Book.GetBooksDataSet().Tables[0];

            CommandField cf = new CommandField();
            cf.ShowEditButton = true;

            GridView1.Columns.Add(cf);

            int colCount = 1;
            foreach (DataColumn c in dataTable.Columns)
            {
                BoundField boundField = new BoundField();

                boundField.DataField = c.ColumnName;
                boundField.HeaderText = c.ColumnName;
                //boundField.FooterText = "---";

                if (colCount == 3 || colCount == 5)
                {
                    boundField.ReadOnly = true;
                }

                GridView1.Columns.Add(boundField);
                colCount++;
            }

            GridView1.ShowFooter = true;

            GridView1.DataSource = dataTable;
            GridView1.DataBind();

            GridViewRow footerRow = GridView1.FooterRow;
            Button b = new Button();
            b.Text = "Add New";
            int i = 0;
            footerRow.Cells[i].Controls.Add(b);
            foreach (DataColumn c in dataTable.Columns)
            {
                ++i;
                TextBox tb = new TextBox();
                footerRow.Cells[i].Controls.Add(tb);
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);

            if (e.CommandName == "Edit")
            {
                //Takes the GridView to Edit mode.
                GridView1.EditIndex = index;

                GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];

                //We can get cell data like this
                string id = selectedRow.Cells[1].Text;
                string isbn = selectedRow.Cells[2].Text;

                //This is necessary to GridView to be showed up.
                CreateGridView();
            }
            else if (e.CommandName == "Update")
            {
                LinkButton updateButton = (LinkButton)e.CommandSource;

                DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;

                GridViewRow gvr = (GridViewRow)dcfc.Parent;

                //The update...................
                //Update grid-data to database
                UpdateDataInTheDatabase(gvr.Cells[1].Controls);                

                //Grid goes back to normal
                GridView1.EditIndex = -1;

                //This is necessary to GridView to be showed up.
                CreateGridView();
            }
        }

        private void UpdateDataInTheDatabase(ControlCollection cc)
        {
            TextBox tb = (TextBox)cc[0];
            //...
            //...
            //...

            //Call the update persistance code here...
        }

        #region Application Satisfactory Event Handlers
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
        }
        #endregion
    }
}

Ответы [ 2 ]

3 голосов
/ 20 августа 2009

для задачи № 1, попробуйте

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
        GridView1.DataSource = Course.GetCourses();
        GridView1.DataBind();
        }
    }

для проблемы # 2, нам нужно проверить ваш метод Course.Update(item).

0 голосов
/ 11 июля 2012
//To Add Esit,Update,Cancel in gridview control ..... 
//source 
<asp:CommandField ShowEditButton="True" HeaderText="Edit Product Name &amp; Price" />

//c# code
  public void gris()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand("select * from Product_details", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            Gridview1.DataSource = ds;
            Gridview1.DataBind();
            con.Close();
        }
 protected void Gridview1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Gridview1.EditIndex = e.NewEditIndex;
            gris();
        }

        protected void Gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Gridview1.EditIndex = -1;
            gris();
        }

        protected void Gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string id = addproduct2.DataKeys[e.RowIndex].Value.ToString();
            string name = ((TextBox)addproduct2.Rows[e.RowIndex].Cells[1].Controls[0]).Text;//(or)Controls[1]
            string rate = ((TextBox)addproduct2.Rows[e.RowIndex].Cells[4].Controls[0]).Text;//(or)Controls[1]
            con.Open();
            cmd = new SqlCommand("update Product_details set product_name='" + name + "',Product_rate='" + rate + "',product_unitprice='" + rate + "' where product_id='" + id + "'", con);
            int i = cmd.ExecuteNonQuery();
            if (i >= 1)
            {
                Response.Write("Updated");
            }
            con.Close();
            Gridview1.EditIndex = -1;
            gris();

        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...