Posted by Nazar Rizvi on 10/5/2007 5:26 AM | Comments (4)

I was trying to find a solution which did bulk updating for all the rows in a gridview, as the gridview provided by VS2005 had its usability issue (at least that's what I thought). After doing some googling I found a set of different grid views available at codeplex called 'ASP.NET Real World Controls'.

Its got a BulkEditGridView, FrozenGridView, GroupingGridView, InlineInsertGridView and TwoHeadedGridView. You can get a hold of the .dll file from http://www.codeplex.com/ASPNetRealWorldContr.
Here is an example of bulk edit grid view.

<cc1:BulkEditGridView ID="BulkEditGridView1" runat="server" AutoGenerateColumns="False"            

DataKeyNames="CategoryID" DataSourceID="AccessDataSource1" EnableInsert="False"            

InsertRowCount="1" SaveButtonID="Button1" AllowPaging="True" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" Width="502px"><Columns>

<asp:BoundField ReadOnly="True" DataField="CategoryID" InsertVisible="False" SortExpression="CategoryID" HeaderText="CategoryID"></asp:BoundField>

<asp:BoundField DataField="CategoryName" SortExpression="CategoryName" HeaderText="CategoryName"></asp:BoundField>

<asp:BoundField DataField="Description" SortExpression="Description" HeaderText="Description"></asp:BoundField>

</Columns>            

<FooterStyle BackColor="Tan" />            

<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />            

<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />            

<HeaderStyle BackColor="Tan" Font-Bold="True" />            

<AlternatingRowStyle BackColor="PaleGoldenrod" /> </cc1:BulkEditGridView>        

<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Nwind.mdb"            

DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = ?" InsertCommand="INSERT INTO [Categories] ([CategoryID], [CategoryName], [Description]) VALUES (?, ?, ?)"             SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"            

UpdateCommand="UPDATE [Categories] SET [CategoryName] = ?, [Description] = ? WHERE [CategoryID] = ?">             <DeleteParameters>                 <asp:Parameter Name="CategoryID" Type="Int32" />             </DeleteParameters>            

<UpdateParameters>                 <asp:Parameter Name="CategoryName" Type="String" />                

<asp:Parameter Name="Description" Type="String" />                 <asp:Parameter Name="CategoryID" Type="Int32" />            

 </UpdateParameters>             <InsertParameters>                 <asp:Parameter Name="CategoryID" Type="Int32" />      

           <asp:Parameter Name="CategoryName" Type="String" />                 <asp:Parameter Name="Description" Type="String" />             </InsertParameters>         </asp:AccessDataSource>         <asp:Button ID="Button1" runat="server" Text="Update" Width="200px" />

 


You just need to make sure that you changed the SaveButtonID property to the button's ID.


 

Comments (4) -

Vikas
Vikas India on 6/7/2008 11:40 PM Hi Nazar Rizvi,

Your post is very helpful... But I want to include a Edit button in the application, and upon clicking the edit button, the grid should become editable. Pls advise me on how to do this with this Bulk Edit Grid.

Thanks

Vikas
shruthi
shruthi United States on 5/31/2011 12:04 AM Hi.. In gridview i have 3 rows month,working days, holidays, and 12 columns..
month is readonly.. other two rows of textboxes should be editable on page load..
i have two enter working days and holidays for corresponding month then save all 12
rows of record on pressing only one save button.. please help me.. if possible mail me... shrusharan@gmail.com . thanks in advance
Kwex
Kwex United Kingdom on 6/2/2011 7:19 AM Hi,

After spending days coming up with an alternative solution for this, I finally arrived at this.

<<Not sure it is the most efficient way of doing it though, but it sure works!>>

<<Default.aspx.cs>>
namespace WebApplication1
{
    public partial class _Default : Page
    {
        private readonly LoadManager _manager = new LoadManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Populate Checkboxes
                PopulateCheckBox();

                //Reset Wizard
                Wizard1.ActiveStepIndex = 0;
            }

            if (IsPostBack)
            {
                RebindGrid();
            }
        }

        private void BindGrid()
        {
            var brokers = _manager.GetBrokers();
            var dataTable = brokers.ToDataTable();

            //Add Checked Columns
            foreach (var item in chkSelection.Items.Cast<ListItem>().Where(item => item.Selected))
            {
                //Add Column
                dataTable.Columns.Add(new DataColumn(item.Text, typeof (string)));
            }

            //Bind to Grid
            BindToGrid(dataTable);
        }

        private static int GetRowIndex(DataTable dataTable, string col, string val)
        {
            var rowIndex = 0;
            foreach (DataRow row in dataTable.Rows)
            {
                if (row[col].ToString() == val) return rowIndex;
                rowIndex++;
            }

            return rowIndex;
        }

        private void RebindGrid()
        {
            //Get from ViewState
            var dataTable = (DataTable) ViewState["DataTable"];
            if (dataTable == null) return;

            for (var rowIndex = 0; rowIndex < GrdDynamic.Rows.Count; rowIndex++)
            {
                var index1 = rowIndex;

                //Get Checked Columns
                var cols = from ListItem col in chkSelection.Items
                           where col.Selected
                           select new
                           {
                               TextBox = (TextBox)GrdDynamic.Rows[index1].FindControl(col.Text),
                               col.Text
                           };

                //Loop thru
                foreach (var col in cols.Where(col => col.TextBox != null && col.TextBox.Text != ""))
                {
                    var lbl = (Label) GrdDynamic.Rows[rowIndex].Cells[0].FindControl("BrokerId");
                    if (lbl == null) continue;
                    var idx = GetRowIndex(dataTable, "BrokerId", lbl.Text);
                    
                    //Store in DataTable
                    dataTable.Rows[idx][col.Text] = col.TextBox.Text;
                }
            }

            //Save changes to ViewState
            ViewState["DataTable"] = dataTable;

            //Bind to Grid
            BindToGrid(dataTable);
        }

        private bool IsChecked(string col)
        {
            return chkSelection.Items.Cast<ListItem>().Any(item => item.Selected && item.Text == col);
        }

        private void BindToGrid(DataTable dt)
        {
            if (dt == null) return;

            //Clear Grid
            GrdDynamic.Columns.Clear();

            //Iterate through the columns of the datatable to set the data bound field dynamically.
            foreach (DataColumn col in dt.Columns)
            {
                //Declare the bound field and allocate memory for the bound field.
                var bfield = new TemplateField();

                if (col.ColumnName == "EntityState" || col.ColumnName == "EntityKey") continue;

                if (IsChecked(col.ColumnName))
                {
                    bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
                    bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName, "TextBox");
                }
                else
                {
                    //Initalize the DataField value.
                    bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);

                    //Initialize the HeaderText field value.
                    bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
                }

                //Add the newly created bound field to the GridView.
                GrdDynamic.Columns.Add(bfield);
            }

            //Initialize the DataSource
            GrdDynamic.DataSource = dt;

            //Store in Viewstate
            ViewState["DataTable"] = dt;

            //Bind the datatable with the GridView.
            GrdDynamic.Columns[0].Visible = false;
            GrdDynamic.DataBind();
        }

        private void PopulateCheckBox()
        {
            var ls = new Dictionary<int, string>
                         {
                             {1, "Selection1"},
                             {2, "Selection2"},
                             {3, "Selection3"},
                             {4, "Selection4"},
                             {5, "Selection5"}
                         };

            //var ss = new List<string> {"Selection1", "Selection1"};

            chkSelection.DataTextField = "value";
            chkSelection.DataValueField = "key";

            chkSelection.DataSource = ls;
            chkSelection.DataBind();
        }

        protected void btn_go_Click(object sender, EventArgs e)
        {
            //Grid();

            //ctl00$MainContent$GrdDynamic$ctl02$ctl02
            //for (int rowIndex = 0; rowIndex < GrdDynamic.Rows.Count; rowIndex++)
            //{
            //    int index = rowIndex;
            //    foreach (TextBox textBox in from ListItem col in chkSelection.Items
            //                                where col.Selected
            //                                select (TextBox) GrdDynamic.Rows[index].FindControl(col.Text))
            //    {
            //        if (textBox != null)
            //        {
            //            Response.Write("<br/>Yep: " + rowIndex + " value: " + textBox.Text);
            //        }
            //        else
            //        {
            //            Response.Write("<br/>Nada: " + rowIndex);
            //        }
            //    }
            //}

            RebindGrid();
        }

        protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (e.NextStepIndex == 1)
            {
                BindGrid();
            }

            if (e.NextStepIndex == 2)
            {
                RebindGrid();
            }
        }

        protected void Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (e.NextStepIndex == 1)
            {
                //RebindGrid();
            }
        }

        protected void GrdDynamic_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GrdDynamic.PageIndex = e.NewPageIndex;

            //Re-bind grid
            RebindGrid();
        }
    }
}
<<End of Default.aspx.cs>>

<<Convert.cs>>
    public static class Convert
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof (T));
            var table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                //table.Columns.Add(prop.Name, prop.PropertyType);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
            var values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    //values[i] = props[i].GetValue(item);
                    values[i] = props[i].GetValue(item) ?? DBNull.Value;
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }
<<End of Convert.cs>>

<<GridViewTemplate.cs>>
    //A customized class for displaying the Template Column
    public class GridViewTemplate : ITemplate
    {
        //A variable to hold the type of ListItemType.
        //A variable to hold the column name.
        private readonly string _columnName;
        private readonly string _boxType;
        private readonly string _dataItem;
        private readonly ListItemType _templateType;

        public GridViewTemplate(ListItemType type, string colname)
        {
            //Stores the template type.
            _templateType = type;

            //Stores the column name.
            _columnName = colname;
        }

        //Constructor where we define the template type and column name.
        public GridViewTemplate(ListItemType type, string colname, string boxType/*, string dataItem*/)
        {
            //Stores the template type.
            _templateType = type;

            //Stores the column name.
            _columnName = colname;

            _boxType = boxType;
            //_dataItem = dataItem;
        }

        #region ITemplate Members

        void ITemplate.InstantiateIn(Control container)
        {
            switch (_templateType)
            {
                case ListItemType.Header:

                    //Creates a new label control and add it to the container.
                    var lbl = new Label {Text = _columnName}; //Allocates the new label object.
                    container.Controls.Add(lbl); //Adds the newly created label control to the container.

                    break;


                case ListItemType.Item:

                    if (_boxType == "TextBox")
                    {
                        //Creates a new text box control and add it to the container.
                        var tb1 = new TextBox(); //Allocates the new text box object.
                        tb1.DataBinding += tb1_DataBinding; //Attaches the data binding event.
                        tb1.ID = _columnName;
                        tb1.Columns = 12;
                        container.Controls.Add(tb1); //Adds the newly created textbox to the container.
                    }else
                    {
                        var lbl2 = new Label(); //Allocates the new label object.
                        lbl2.DataBinding += lbl_DataBinding; //Attaches the data binding event.
                        lbl2.ID = _columnName;
                        //tb1.Width = 4; //Creates a column with size 4.
                        container.Controls.Add(lbl2);
                    }

                    break;


                case ListItemType.EditItem:

                    //As, I am not using any EditItem, I didnot added any code here.
                    break;

                case ListItemType.Footer:

                    var chkColumn = new CheckBox();
                    chkColumn.ID = "Chk" + _columnName;
                    container.Controls.Add(chkColumn);

                    break;
            }
        }

        #endregion

        /// <summary>
        /// This is the event, which will be raised when the binding happens.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tb1_DataBinding(object sender, EventArgs e)
        {
            var txtdata = (TextBox) sender;
            var container = (GridViewRow) txtdata.NamingContainer;
            object dataValue = DataBinder.Eval(container.DataItem, _columnName);
            //object dataValue = DataBinder.Eval(container.DataItem, _dataItem);

            if (dataValue != DBNull.Value)
            {
                txtdata.Text = dataValue.ToString();
            }
        }

        private void lbl_DataBinding(object sender, EventArgs e)
        {
            var lbldata = (Label)sender;
            var container = (GridViewRow)lbldata.NamingContainer;
            object dataValue = DataBinder.Eval(container.DataItem, _columnName);

            //if (dataValue != DBNull.Value && dataValue != null)
            if (dataValue != DBNull.Value)
            {
                lbldata.Text = dataValue.ToString();
            }
        }
    }

<<End of GridViewTemplate.cs>>
Nazar Rizvi
Nazar Rizvi United States on 6/2/2011 10:20 PM Hi Shruthi,

Please use jqGrid. It is a very good jquery grid control with lots of flexibility. Normal GridView is very outdated.

http://www.trirand.net/demoaspnet.aspx

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading