Guest User

StackOverFlow http://stackoverflow.com/q/31848021/1641556

a guest
Aug 6th, 2015
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. //http://stackoverflow.com/q/31848021/1641556
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Windows.Forms;
  11.  
  12. namespace DataTableDuplicateValuesCheck
  13. {
  14.     public partial class Form1 : Form
  15.     {
  16.         public Form1()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         //used .net framework 4
  21.         //add single textbox,datagridview and button into form.
  22.        
  23.         private void Form1_Load(object sender, EventArgs e)
  24.         {
  25.             DataTable dt = new DataTable();
  26.             dt.Columns.Add("Item Code", typeof(string));
  27.             dataGridView1.DataSource = dt;
  28.         }
  29.  
  30.         private void button1_Click(object sender, EventArgs e)
  31.         {
  32.             bool isDuplicate = false;
  33.             DataTable refTable = (DataTable)dataGridView1.DataSource;
  34.            
  35.             // What i needs to do,
  36.             // to improve the performance by removing foreach with linq
  37.             //I dont not it can be done or not or it can improve the performance by using linq.
  38.             // your coments are welcome.....
  39.     #region replace_this_code_with_linq
  40.             foreach (DataRow r in refTable.Rows)
  41.             {
  42.                 if (r["Item Code"].ToString() == textBox1.Text) {
  43.                     isDuplicate = true;
  44.                 }
  45.             }
  46.     #endregion
  47.             if (!isDuplicate)
  48.             {
  49.                 DataRow row = refTable.NewRow();
  50.                 row["Item Code"] = textBox1.Text;
  51.                 refTable.Rows.Add(row);
  52.                 dataGridView1.DataSource = refTable;
  53.             }
  54.             else {
  55.                 MessageBox.Show(string.Format("This item ({0}) already added!",textBox1.Text));
  56.             }  
  57.  
  58.         }        
  59.        
  60.     }
  61. }
Add Comment
Please, Sign In to add comment