.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> DataGrid >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Add Or Row Datagridview in C#

Posted By:Narayanan       Posted Date: December 06, 2012    Points: 40    Category: DataGrid    URL: http://www.dotnetspark.com  

Today , We will learn How to add Row(s) in the Datagridview when user clicks CheckedListBox Item Checked using C#.Net
 

Try this Code:
 public void AddorRemoveRows(DataGridView DGV, CheckedListBox chk, string Mode)
        {
            try
            {
                switch (Mode)
                {
                    case "Add":
                        if (chk.SelectedItem.ToString() != null)
                        {
                            string SelectedItem = chk.SelectedItem.ToString();
                            DGV.RowCount = DGV.RowCount + 1;
                            DGV.Rows[DGV.RowCount - 1].Cells[0].Value = SelectedItem;
                            chk.SelectedIndex = -1;
                        }
                        break;
                    case "Remove":
                        string UnSelectedItem = chk.SelectedItem.ToString();
                        int SelectedIndex = RowId(UnSelectedItem, DGV);
                        DGV.Rows.RemoveAt(SelectedIndex);
                        break;

                }
            }
            catch (Exception ex)
            {
                Program.WriteLog(ex.Message, ex.StackTrace);
            }

        }
        int rowId;
        private int RowId(string unSelectedItem, DataGridView dgv)
        {

            for (int rowidx = 0; rowidx < dgv.Rows.Count; rowidx++)
            {
                if (unSelectedItem == Convert.ToString(dgv.Rows[rowidx].Cells[0].Value))
                {
                    rowId = rowidx;
                    break;
                }
            }
            return rowId;
        }


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend