SharePointCommunity
Die deutschsprachige Community für SharePoint, Microsoft 365, Teams, Yammer und mit Azure

Sponsored by

Willkommen im Forum Archiv.
Einträge sind hier nicht mehr möglich, aber der Bestand von 12 Jahren SharePoint-Wissen ist hier recherchierbar.




SPGridView add New Row

Unbeantwortet Dieser Beitrag hat 0 Antworten

Ohne Rang
1 Beiträge
dineshde erstellt 4 Nov. 2014 16:42
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Hallo Sharepointcommunity,

I am Struggling with this problem for long time. I don't how to do this. I want display a gridview inside the webpart and its working perfectly and also editing, updating working perfectly but the inserting new row is not working. 

 

My objectDatasource looks like this 

 

 public class SPgrid : CompositeControl

    {

       private Basic _basic;

       private ObjectDataSource _gridDS;

       private SPGridView _grid; 

 

       public SPgrid(Basic basic)

       {

           _basic = basic;

       }

       protected sealed override void CreateChildControls()

       {

 

           const string GRIDID = "grid";

           const string DATASOURCEID = "gridDS";

 

           _gridDS = new ObjectDataSource();

           _gridDS.ID = DATASOURCEID;

           _gridDS.TypeName = typeof(Basic).AssemblyQualifiedName;

 

           _gridDS.SelectMethod = "Select";

           _gridDS.ObjectCreating += new ObjectDataSourceObjectEventHandler(gridDS_ObjectCreating);

 

 

           _gridDS.InsertMethod = "Insert";

           _gridDS.Inserting += new ObjectDataSourceMethodEventHandler(gridDS_Inserting);

 

            // to handle updates from the grid

           _gridDS.UpdateMethod = "Update";

           _gridDS.Updating += new ObjectDataSourceMethodEventHandler(gridDS_Updating);

 

           this.Controls.Add(_gridDS);

 

           // create our grid

           _grid = new SPGridView();

           _grid.ID = GRIDID;

           _grid.DataSourceID = _gridDS.ID; // link the grid to the ObjectDataSource

           _grid.AutoGenerateColumns = false; // must be false

 

           // generally the primary key field(s)

           // these will be passed as an input parameter

           _grid.DataKeyNames = _basic.GetDataKeyNames();

 

 

           // add the column that will allow editing

           CommandField command = new CommandField();

           command.ShowInsertButton = true;

           command.ShowEditButton = true;

           _grid.Columns.Add(command);

 

           // add all of the columns in the datatable to the grid

           // any column that is not readonly will be passed as an input parameter

           foreach (BoundField column in _basic.GetColumns())

           {

               _grid.Columns.Add(column);

           }

 

           this.Controls.Add(_grid);

       }

 

       void gridDS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)

       {

 

           Dictionary<string, string> data = new Dictionary<string, string>();

 

           foreach (DictionaryEntry entry in e.InputParameters)

           {

               string value = entry.Value == null ? null : entry.Value.ToString();

               data.Add(entry.Key.ToString(), value);

           }

 

           e.InputParameters.Clear();

           e.InputParameters.Add("data", data);

       }

 

       /// <summary>

    /// Consolidates all of the InputParameters (values from the grid)

    /// into one dictionary of values to send to the update method

    /// </summary>

    void gridDS_Updating(object sender, ObjectDataSourceMethodEventArgs e)

    {

        Dictionary<string, string> data = new Dictionary<string, string>();

 

        foreach (DictionaryEntry entry in e.InputParameters)

        {

            string value = entry.Value == null ? null : entry.Value.ToString();

            data.Add(entry.Key.ToString(), value);

        }

 

        e.InputParameters.Clear();

        e.InputParameters.Add("data", data);

    }

 

    /// <summary>

    /// When the ObjectDataSource is created, hook it up to the Logic class

    /// (so that it uses the Logic class to make the Select, Update... calls)

    /// </summary>

    private void gridDS_ObjectCreating(object sender, ObjectDataSourceEventArgs e)

    {

        e.ObjectInstance = _basic;

    }

}

 

  The Basic class which i used above looks like this

 

public class Basic

    {

        const string LIST_NAME = "Invoice Positions";

        readonly string[] LIST_COLUMNS = null;

        readonly string VIEW_FIELDS = string.Empty;

        readonly string[] DATA_KEY_NAMES = null;

        private SPWeb _currentWeb;

        String invoicenos;

        public Basic(SPWeb currentWeb, String invoiceno)

        {

            invoicenos = invoiceno;

            _currentWeb = currentWeb;

            DATA_KEY_NAMES = new string[1];

            DATA_KEY_NAMES[0] = "ID";

            LIST_COLUMNS = new string[5];

            LIST_COLUMNS[0] = "InvoicePosAmountNet";

            LIST_COLUMNS[1] = "InvoicePosPreTax";

            LIST_COLUMNS[2] = "InvoicePosPurchOrderID";

            LIST_COLUMNS[3] = "InvoicePosText";

            LIST_COLUMNS[4] = "PurchOrderPosID";

            VIEW_FIELDS = GetViewFields(LIST_COLUMNS);

        }

 

        public string[] GetDataKeyNames()

        {

            return DATA_KEY_NAMES;

        }

        public List<BoundField> GetColumns()

        {

            List<BoundField> fields = new List<BoundField>();

            fields.Add(GetBoundField("InvoiceID"));

            // we don't want the ID field to be editable so we make it readonly

            // readonly will mean a textbox to edit it will not be shown

            fields[0].ReadOnly = true;

            fields.Add(GetBoundField("InvoicePosAmountNet"));

            fields.Add(GetBoundField("InvoicePosPreTax"));

            fields.Add(GetBoundField("InvoicePosPurchOrderID"));

            fields.Add(GetBoundField("InvoicePosText"));

            fields.Add(GetBoundField("PurchOrderPosID"));

            return fields;

        }

 

        private BoundField GetBoundField(string name)

        {

            // do not use SPBoundField (will not work with editing)

            BoundField bf = new BoundField();

            bf.HeaderText = name;

            bf.DataField = name;

            return bf;

        }

 

        public DataTable Select()

        {

            DataTable t = new DataTable();

            SPSecurity.RunWithElevatedPrivileges(delegate()

            {

                using (SPSite site = new SPSite(_currentWeb.Site.ID))

                {

                    using (SPWeb web = site.OpenWeb(_currentWeb.ID))

                    {

                        SPQuery query = new SPQuery();

                        query.Query = "<Where><Eq><FieldRef Name='InvoiceID'/>" +

                                         "<Value Type='Number'>" + invoicenos + "</Value></Eq></Where>";

                        SPList list = _currentWeb.Lists[LIST_NAME];

                        SPListItemCollection items = list.GetItems(query);

                        t = items.GetDataTable();

                    }

                }

            });

 

            return t;

        }

 

        private string GetViewFields(string[] columns)

        {

            StringBuilder sb = new StringBuilder();

            foreach (string field in columns)

            {

                sb.AppendFormat("<FieldRef Name='{0}' />", field);

            }

            return sb.ToString();

        }

 

        public void Insert(Dictionary<string, string> data)

        {

            SPSecurity.RunWithElevatedPrivileges(delegate()

      {

          using (SPSite site = new SPSite(_currentWeb.Site.ID))

          {

              using (SPWeb web = site.OpenWeb(_currentWeb.ID))

              {

                  SPList list = _currentWeb.Lists[LIST_NAME];

                  SPListItem item = list.Items.Add();

                  item["InvoicePosAmountNet"] = data["InvoicePosAmountNet"];

                  item["InvoicePosPreTax"] = data["InvoicePosPreTax"];

                  item["InvoicePosPurchOrderID"] = data["InvoicePosPurchOrderID"];

                  item["InvoicePosText"] = data["InvoicePosText"];

                  item["PurchOrderPosID"] = data["PurchOrderPosID"];

                  item.Update();

              }

          }

      });

 

        }

        public void Update(Dictionary<string, string> data)

        {

            SPSecurity.RunWithElevatedPrivileges(delegate()

      {

          using (SPSite site = new SPSite(_currentWeb.Site.ID))

          {

              using (SPWeb web = site.OpenWeb(_currentWeb.ID))

              {

                  SPList list = _currentWeb.Lists[LIST_NAME];

                  int id = Int32.Parse(data["ID"]);

                  SPListItem item = list.GetItemById(id);

                  item["InvoicePosAmountNet"] = data["InvoicePosAmountNet"];

                  item["InvoicePosPreTax"] = data["InvoicePosPreTax"];

                  item["InvoicePosPurchOrderID"] = data["InvoicePosPurchOrderID"];

                  item["InvoicePosText"] = data["InvoicePosText"];

                  item["PurchOrderPosID"] = data["PurchOrderPosID"];

                  item.Update();

              }

          }

      });

 

 

        }

 

  The createchildcontrol of my webpart looks like this 

 

public class Invoiceposition : WebPart

    {

        private SPgrid gird = null; 

            protected override void CreateChildControls()

        {

            base.CreateChildControls();

 

                string invoiceno = Page.Request.QueryString.Get("invoicenumber");

                Basic basiccode = new Basic(SPControl.GetContextWeb(Context), invoiceno);

                if (gird == null)

                {

                    gird = new SPgrid(basiccode);

 

 

                }

                this.Controls.Add(gird);

 

 

        }