reiterate through a gridview table

5 posts, 1 answers
  1. John
    John avatar
    4 posts
    Member since:
    May 2013

    Posted 13 May 2013 Link to this post

    Hi,

    I am designing a purchase order form and using a GridView to input the order. I have an insert, remove row, and a submit buttons. The idea is that the user will click on insert a new row, enter data, insert a row, enter data, etc

    once the user has added the items to the grid I need to reiterate through the grid and insert the data row by row into an SQL database. I can insert the current row but not sure how to reiterate through the grid using For each row, etc

    Any advice is much appreciated.

    Regards,

    John


    private void radButtonSubmitOrder_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
     
            dataModel dbstring = new dataModel();
     
            conn.ConnectionString = dbstring.getDBConnString();
            conn.Open();
     
            string _insertData = "insert into Items(FormID,Item,Description,UnitsOrdered,UnitCost) values (@FormID,@Item,@Description,@UnitsOrdered,@UnitCost)";
     
            try
            {
                SqlCommand cmd = new SqlCommand(_insertData, conn);
     
                    
                cmd.Parameters.Add("@FormID", SqlDbType.Int);
                cmd.Parameters.Add("@Item", SqlDbType.Text);
                cmd.Parameters.Add("@Description", SqlDbType.Text);
                cmd.Parameters.Add("@UnitsOrdered", SqlDbType.Int);
                cmd.Parameters.Add("@Unitcost", SqlDbType.Money);
        
                 
                cmd.Parameters["@FormID"].Value = "567891";
                cmd.Parameters["@Item"].Value = this.radGridView1.CurrentRow.Cells[0].Value;
                cmd.Parameters["@Description"].Value = this.radGridView1.CurrentRow.Cells[1].Value;
                cmd.Parameters["@UnitCost"].Value = this.radGridView1.CurrentRow.Cells[2].Value;
                cmd.Parameters["@UnitsOrdered"].Value = this.radGridView1.CurrentRow.Cells[3].Value;
           
        
                cmd.ExecuteNonQuery();
            }
            catch (System.Data.SqlClient.SqlException sqlException)
            {
                // Write error to Debug output stream
                System.Diagnostics.Debug.Write(sqlException.Message);
            }
     
            finally
            {
                conn.Close();
     
            }
     
        }
  2. Emanuel Varga
    Emanuel Varga avatar
    1336 posts
    Member since:
    May 2010

    Posted 14 May 2013 Link to this post

    Hello John,

    You can use the Rows collection to iterate through the rows and the Cells for each row to get the value for the individual cells.

    var stringBuilder = new StringBuilder();
     
    foreach (var row in gridView.Rows)
    {
        foreach (GridViewCellInfo cell in row.Cells)
        {
            var value = cell.Value;
            stringBuilder.Append(value != null ? value.ToString() : "N/A");
            stringBuilder.Append(" | ");
        }
        stringBuilder.AppendLine();
    }
     
    MessageBox.Show(stringBuilder.ToString());

    But i would suggest, if possible, binding the grid to a collection and thus get the data from the underlying collection instead of iterating trough the rows. If you need help on this please let me know.

    Best Regards,
    Emanuel Varga, MVP
  3. UI for WinForms is Visual Studio 2017 Ready
  4. John
    John avatar
    4 posts
    Member since:
    May 2013

    Posted 14 May 2013 Link to this post

    Hi Emanuel,

    I don't appear to have access to the 'GridViewCellInfo' class to try your example. I have a reference to Telerik.WinControls.

    Please can you assist me in binding my grid to a collection.

    Kind regards,

    John

  5. Answer
    Emanuel Varga
    Emanuel Varga avatar
    1336 posts
    Member since:
    May 2010

    Posted 15 May 2013 Link to this post

    Hello again John,

    Please take a look at the following example:
    using grid_iterate_grid.Annotations;
    using System;
    using System.ComponentModel;
    using System.Text;
    using System.Windows.Forms;
    using Telerik.WinControls.UI;
     
    namespace grid_iterate_grid
    {
        public partial class Form1 : Form
        {
            private RadGridView gridView = new RadGridView();
     
            private BindingList<TestClass> dataSource = new BindingList<TestClass>();
     
            public Form1()
            {
                InitializeComponent();
                var parseGrid = new RadButton();
     
                parseGrid.Text = "Parse!";
                parseGrid.Dock = DockStyle.Bottom;
                parseGrid.Click += parseGrid_Click;
                this.Controls.Add(parseGrid);
     
                var addProgramaticallyButton = new RadButton();
     
                addProgramaticallyButton.Text = "Add row programatically!";
                addProgramaticallyButton.Dock = DockStyle.Bottom;
                addProgramaticallyButton.Click += addProgramaticallyButton_Click;
                this.Controls.Add(addProgramaticallyButton);
     
                //gridView.Columns.Add(new GridViewTextBoxColumn());
                //gridView.Columns.Add(new GridViewDecimalColumn());
                //gridView.Columns.Add(new GridViewDateTimeColumn());
                gridView.Dock = DockStyle.Fill;
                gridView.DataSource = dataSource;
                this.Controls.Add(gridView);
            }
     
            private void addProgramaticallyButton_Click(object sender, EventArgs e)
            {
                dataSource.Add(new TestClass { Id = 1000, Date = DateTime.Now, Name = "Programatically added!" });
            }
     
            private void parseGrid_Click(object sender, EventArgs e)
            {
                var stringBuilder = new StringBuilder();
     
                // old version
                //foreach (var row in gridView.Rows)
                //{
                //    foreach (GridViewCellInfo cell in row.Cells)
                //    {
                //        var value = cell.Value;
                //        stringBuilder.Append(value != null ? value.ToString() : "N/A");
                //        stringBuilder.Append(" | ");
                //    }
                //    stringBuilder.AppendLine();
                //}
     
                foreach (var testClass in dataSource)
                {
                    stringBuilder.AppendLine(string.Format("Id: {0}, Name: {1}, Date: {2}", testClass.Id, testClass.Name,
                                                           testClass.Date));
                }
     
                MessageBox.Show(stringBuilder.ToString());
            }
     
            public class TestClass : INotifyPropertyChanged
            {
                private DateTime date;
                private string name;
                private int id;
     
                public int Id
                {
                    get { return id; }
                    set
                    {
                        if (value == id) return;
                        id = value;
                        OnPropertyChanged("Id");
                    }
                }
     
                public string Name
                {
                    get { return name; }
                    set
                    {
                        if (value == name) return;
                        name = value;
                        OnPropertyChanged("Name");
                    }
                }
     
                public DateTime Date
                {
                    get { return date; }
                    set
                    {
                        if (value.Equals(date)) return;
                        date = value;
                        OnPropertyChanged("Date");
                    }
                }
     
                public event PropertyChangedEventHandler PropertyChanged;
     
                [NotifyPropertyChangedInvocator]
                protected virtual void OnPropertyChanged(string propertyName)
                {
                    PropertyChangedEventHandler handler = PropertyChanged;
                    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    }

    Hope this helps, if you have any more questions please don't hesitate to ask.

    If this answers your question, please mark all relevant answers.

    Best Regards.
    Emanuel Varga, MVP
  6. John
    John avatar
    4 posts
    Member since:
    May 2013

    Posted 16 May 2013 Link to this post

    Hi Emanuel,

    I like this method!

    Thanks for your support!

    Regards,

    JOhn
Back to Top
UI for WinForms is Visual Studio 2017 Ready