public Form1()
        {
            InitializeComponent();
            DataTable people = new DataTable();
            people.Columns.Add("id");
            people.Columns.Add("Name");

            people.Rows.Add(1, "John Smith");
            people.Rows.Add(2, "Jane Doe");
            people.Rows.Add(3, "Foo Bar");
            people.Rows.Add(4, "Justin Time");
            people.Rows.Add(5, "Imma Mann");

            DataTable table = new DataTable();
            table.Columns.Add("PeopleName");
            table.Columns.Add("PeopleCallPhone");

            table.Rows.Add("John Smith","123-456-7890");
            table.Rows.Add("Jane Doe", "234-567-8900");
            table.Rows.Add("Foo Bar", "345-678-9000");
            table.Rows.Add("Justin Time", "456-789-0000");
            table.Rows.Add("Imma Mann", "567-890-0000");


            var col = new DataGridViewComboBoxColumn();
            col.Name = "PeopleName";
            col.DataPropertyName = "PeopleName";
            col.HeaderText = "Name";
            col.DataSource = people;
            col.DisplayMember = "Name";
            col.ValueMember = "Name";

            this.dataGridView1.Columns.Add(col);
            this.dataGridView1.DataSource = table;
            this.dataGridView1.Columns[1].HeaderText = "Phone";
        }

'Language > C#' 카테고리의 다른 글

Dictionary 연습  (0) 2020.02.12
[C#] 문자열 엔터처리하기  (0) 2020.02.12
[C#] LINQ 연습 2일  (0) 2020.02.03
[c#]treelistview 노드코드  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31

<Form1.cs>

Dictionary<string, Dictionary<string, bool>> check_confirm = new Dictionary<string, Dictionary<string, bool>>();
        Dictionary<string, bool> check_a = new Dictionary<string, bool>();
        public static Form1 f;
        public Form1()
        {
            InitializeComponent();
            f = this;
            UserControl1 uc = new UserControl1();
            panel1.Controls.Add(uc);

        }
        public void checkvalue(string name, string value, bool check)
        {
            if (check_a.ContainsKey(value)&&check_confirm.ContainsKey(name))
            {
                check_a.Remove(value);
                check_confirm.Remove(name);
            }
            check_a.Add(value, check);
            check_confirm.Add(name,check_a);

            
            Console.WriteLine("테스트중 :: " + check_a[value]) ;
        }

<UserControl1.cs>

//생략
        private void UserControl1_Load(object sender, EventArgs e)
        {
            GroupBox[] grouppanel = new GroupBox[10];
            for (int i = 0; i < 10; i++)
            {
                grouppanel[i] = new GroupBox();
                if (i >= 5 && i != 0)
                {
                    grouppanel[i].Left = 153;
                }
                else
                {
                    grouppanel[i].Left = 53;
                }
                grouppanel[i].Size = new Size(78, 60);
                grouppanel[i].Width = 78;
                grouppanel[i].Height = 60;
                if (i < 5)
                {
                    int a = 10 + (i * 79);
                    grouppanel[i].Top = a;
                }
                else
                {
                    int a = 10 + ((i - 5) * 79);
                    grouppanel[i].Top = a;
                }

                grouppanel[i].Text = i + "번째";

                this.Controls.Add(grouppanel[i]);
            }
            int ia = 0;
            foreach(Control ctl in this.Controls)
            {
                if(ctl.GetType().Name.ToLower() == "groupbox")
                {
                    Button bt = new Button();
                    bt.Text = ia + "bt";
                    bt.Location = new Point(20, 20);
                    bt.Size = new Size(44, 30);
                    bt.Click += Bt_Click;
                    bt.Name = ia.ToString();
                    ctl.Controls.Add(bt);
                }
                ia++;
            }

        }

        private void Bt_Click(object sender, EventArgs e)
        {
            Button click = (Button)sender;
            if(click.BackColor != Color.AliceBlue) { 
            click.BackColor = Color.AliceBlue;
            Form1.f.checkvalue(click.Name, click.Text, true);
            }
            else
            {
                click.BackColor = Color.Gray;
                Form1.f.checkvalue(click.Name, click.Text, false);
            }
        }

UserControl에 groupbox 10개 추가하고 각각의 groupbox에 button을 넣은 후 click 이벤트를 연결해줌

 

각각 버튼이 클릭 된 상태인지 확인하기 위하여 dictionary를 사용함.

 

Dictionary in Dictionary 선언

Dictionary<자료형,Dictionary<자료형,자료형>> dic = new Dictionary<자료형,Dictionary<자료형,자료형>>();

Dictionary 안에 Dictionary 선언이 가능하다.

 

 Dictionary<string, Dictionary<string, bool>> check_confirm = new Dictionary<string, Dictionary<string, bool>>();
 Dictionary<string, bool> check_a = new Dictionary<string,bool>();
 
 check_a.Add("testkey2",false);
 check_confirm.Add("testKey1",check_a);
 
 //check_confirm에 add한 bool값 가져오기
 Console.WriteLine("value::"+check_confirm["testKey1"]["testkey2"]);

Dictonary in Dictionary의 마지막 value를 가져오려면 

Dictionary명[첫번째키][두번째Dictionary키] 로 value를 가져올 수 있다.

'Language > C#' 카테고리의 다른 글

[C#] DataGridViewComboBoxColumn  (0) 2020.03.17
[C#] 문자열 엔터처리하기  (0) 2020.02.12
[C#] LINQ 연습 2일  (0) 2020.02.03
[c#]treelistview 노드코드  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31
String.Replace("\n", "\r\n");

DB에서 가져온 데이터의 개행 처리가 되지 않는 것을 볼 수 있다

C# 개행 \r\n 으로

DB에서 가져온 값의 \n을 replace로 \r\n으로 바꿔준다.

'Language > C#' 카테고리의 다른 글

[C#] DataGridViewComboBoxColumn  (0) 2020.03.17
Dictionary 연습  (0) 2020.02.12
[C#] LINQ 연습 2일  (0) 2020.02.03
[c#]treelistview 노드코드  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31

LINQ에서 쿼리 변수는 쿼리의 결과 대신 쿼리를 저장하는 변수.

쿼리 변수는 항상 foreach문이나 IEnumerator.MoveNext 메서드에 대한 직접 호출에서 반복될 때 요소 시퀀스를 생성하는 Enumerable 형식

 

            int[] scores = { 90, 71, 82, 93, 75, 82 };
            IEnumerable<int> scoreQuery = from score in scores
                                          where score > 80
                                          orderby score descending
                                          select score;
            foreach(int testScore in scoreQuery)
            {
                Console.WriteLine(testScore);
            }

 

 

쿼리 변수 저장 방법 2가지

            IEnumerable<City> queryMajorCities = from city in cities
                                                 where city.Population > 100000
                                                 select city;

            IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 100000);

 

          int[] scores = { 90, 71, 82, 93, 75, 82 };
          
         int hightestScore = (from score in scores 
                              select score).Max();
            IEnumerable<int> scoreQuery = from score in scores
                                          select score;
            int hightScore = scoreQuery.Max();
            int hightScore = scores.Max();

            List<City> largeCitiesList = (from country in countires
                                          from city in country.Cities
                                          where city.Population > 10000
                                          select city).ToList();

            IEnumerable<City> largeCitiesQuery = from country in countries
                                                 from city in country.Cities
                                                 where city.Population > 10000
                                                 select city;

            List<CIty> largeCitiesList2 = largeCities.Query.ToList();

 

쿼리 변수의 명시적 형식 및 암시적 형식

 

일반적으로 쿼리 변수와 select 절 간의 형식 관계를 표시하기 위해 쿼리 변수의 명시적 형식을 제공

그러나 var 키워드를 사용하여 컴파일 시간에 쿼리 변수(또는 다른 지역 변수)의 형식을 추론하도록 컴파일러에 지시할 수도 있음.

    var queryCities = from city in cities
                              where city.Population > 100000
                              select city;

 

 

쿼리 식 시작

 

쿼리 식은 from 절로 시작해야함

쿼리 식은 범위 변수와 함께 데이터 소스를 지정한다.

범위 변수는 소스 시퀀스가 트래버스할 때 소스 시퀀스의 각 연속 요소를 나타낸다.

범위 변수는 데이터 소스의 요소 형식을 기반으로 강력하게 형식지 지정된다.

 

 

  IEnumerable<Country> countryAreQuery = from country in countries
                                                   where country.Area > 500000
                                                   select country;

쿼리가 세미콜론 또는 continuation 절로 종료될 때까지 범위 변수는 범위 내에 있음

 

쿼리 식에는 여러 from 절이 포함될 수 있음.

소스 시퀀스의 각 요소가 컬렉션이거나 컬렉션을 포함하는 경우 from 절을 추가로 사용해야합니다.

ex ) Country 개체의 컬렉션이 있으며, 각각에 Cities라는 이름이 City 개체 컬렉션이 포함되어 있다고 가정

     각 Country에서 City 개체를 쿼리하려면 다음과 같이 두 개의 from 절을 사용합니다.

            IEnumberable<City> cityQuery = from country in coutries
                                           from city in country.Cities
                                           where city.Population > 10000
                                           select city;
								

 

쿼리 식 종료

쿼리 식은 group 절 또는 select 절로 끝나야 합니다.

 

group 절

지정한 키로 구성되는 그룹의 시퀀스를 생성하려면 group 절을 사용

키의 데이터 형식은 무억이든 가능

 

` 다음 쿼리는 하나 이상의 Country 개체를 포함하며 키가 char 값인 그룹의 시퀀스를 만든다

var queryCountryGroups = from country in countries
			group country by country.Name[0];

 

 

select 절

다른 모든 시퀀스 형식을 생성하려면 select 절을 사용한다.

간단한 select 절은 데이터 소스에 포함된 개체와 동일한 개체 형식의 시퀀스를 생성

 

`- 이 예제에서는 데이터 소스에 Country 개체가 포함된다. orderby 절은 단지 요소를 새로운 순서로 정렬하고, select 절은 다시 정렬된 Country 개체의 시퀀스를 생성한다.

IEnumberable<Country> soretedQuery = from country in countries orderby country.Area
				orderby country.Area
				select country;

 

 

'Language > C#' 카테고리의 다른 글

Dictionary 연습  (0) 2020.02.12
[C#] 문자열 엔터처리하기  (0) 2020.02.12
[c#]treelistview 노드코드  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31
[C#] 검색 기능 구현 - 입력하자마자 검색  (0) 2020.01.30
  Public Sub QueryresulttoTreeListView_Project(tv As TreeListView, dt As DataTable, str As String)
        Dim DicTn As Dictionary(Of String, TreeListNode) = New Dictionary(Of String, TreeListNode)
        Dim temp As String = Nothing
        Dim temp_b As Boolean = False
        Dim parentName As String = Nothing
        Dim checked_RB As String

        For i = 0 To dt.Columns.Count - 1
            Dim TempDt As DataTable = dt
            For k = 0 To TempDt.Rows.Count - 1
                Dim TreeNodeName As String = getchildName(TempDt, k, i) 'row 고정, column값 변경하면서 datatable 값 가져옴


                If DicTn.ContainsKey(TreeNodeName) Then
                    Continue For
                Else

                    DicTn(TreeNodeName) = New TreeListNode(TempDt.Rows(k)(i).ToString())
                End If

                If i > 0 Then
                    'parentNode가 있는 경우 자식노드 생성
                    If temp_b = False Then '부모노드인지 자식노드인지 판별하는 boolen
                        'temp_b =  false면 자식노드, true면 부모노드
                        parentName = getchildName(TempDt, k, i - 1) 'parentname 가져오는 부분
                        If String.IsNullOrEmpty(parentName) Then
                            Continue For
                        End If
                        DicTn(parentName).Nodes.Add(DicTn(TreeNodeName)) 'parentnode에 현재 값 add

                    End If
                Else
                    ' 부모/루트 노드 생성
                    'dictionary(TreeNodeName) null체크 및 TreeNodeName null체크
                    If Not DicTn(TreeNodeName) Is Nothing And Not String.IsNullOrEmpty(TreeNodeName) Then
                        If i > 0 Then

                            temp_b = False
                            tv.Nodes.Add(DicTn(TreeNodeName)) 'treelistview에 parent/root 노드 생성

                            'End If
                        Else
                            temp_b = False
                            tv.Nodes.Add(DicTn(TreeNodeName)) 'treelistview에 parent/root 노드 생성

                        End If
                    Else
                        Continue For
                    End If

                End If

            Next

        Next
        nodes = tv.Nodes

        'treelistview 노드 생성 완료 후 결함과 검증에 값을 넣어줌
        For Each node As TreeListNode In tv.Nodes

            Dim defect_dt As Integer = 0
            Ldr_ref = dt.Select("[" + str + "] = '" + node.Text + "'")
            node.SubItems.Add(Ldr_ref.Count.ToString())


            node.SubItems.Add(defect_dt.ToString())

        Next

'Language > C#' 카테고리의 다른 글

[C#] 문자열 엔터처리하기  (0) 2020.02.12
[C#] LINQ 연습 2일  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31
[C#] 검색 기능 구현 - 입력하자마자 검색  (0) 2020.01.30
[C#] textbox keypress 이벤트  (0) 2020.01.30

DatagridView.AllowUserToAddRows = false;

로 설정하면 데이터가 있는 값만 Datagridview에 나타남

'Language > C#' 카테고리의 다른 글

[C#] LINQ 연습 2일  (0) 2020.02.03
[c#]treelistview 노드코드  (0) 2020.02.03
[C#] 검색 기능 구현 - 입력하자마자 검색  (0) 2020.01.30
[C#] textbox keypress 이벤트  (0) 2020.01.30
[C#] LINQ 연습 1일  (0) 2020.01.30

 

<Form1.cs>

//생략      

private void Main_searchTextBox_KeyUp(object sender, KeyEventArgs e) //검색 기능 구현 할 textbox keyup이벤트
        {
            Thread.Sleep(40);

            commonfunction.Main_SearchTextBox(Main_searchTextBox.Text);
        }

 

 

 

<CommonFunction.cs>

String MainSearchResult;



        #region //Main.cs의 검색기능 메소드
        /// <summary>
        /// 검색텍스트박스 keypressEvent를 받아와 처리해 주는 메소드
        /// </summary>
        /// <param name="TextBoxInputValue"> KeypressEvent로 textbox에 입력된 값 </param>
        public void Main_SearchTextBox(String TextBoxInputValue)
        {
            DataTable form1DT_copy = form1.dt; // form1의 datatable form1DT_copy에 복사
            MainSearchResult = TextBoxInputValue;
            IEnumerable<DataRow> linq_row = null;

            DataTable form1DT_re = new DataTable();
            form1DT_re = form1DT_copy.Clone();

            if (MainSearchResult == "")
            {
               form1._dgv.DataSource = form1DT_copy;


            }
            else
            {
                //MainSearchResult가 ""이 아니면 일치하는 데이터 찾는 코드
                foreach (DataRow row in form1DT_copy.Rows)
                {
                    linq_row = from item in row.ItemArray
                               where item.ToString().ToLower().Equals(MainSearchResult.ToLower())
                               select row;
                    //입력된 값이 완전히 일치하는지 확인
                   
                    foreach (DataRow dt in linq_row)
                    {
                        form1DT_re.Rows.Add(dt.ItemArray);
                       
                    }
                  //linq 결과를 datatable에 넣어주는 작업
                }
                //입력된 값이 부분적으로 일치하는 경우 
              if(form1DT_re.Rows.Count== 0)
                {
                    foreach (DataRow row in form1DT_copy.Rows)
                    {
                      
                        linq_row = from item in row.ItemArray
                                   where item.ToString().ToLower().Contains(MainSearchResult.ToLower())
                                   select row;
                        //입력된 값이 부분적으로 일치하는지 확인
                        foreach (DataRow dt in linq_row)
                        {
                            form1DT_re.Rows.Add(dt.ItemArray);
                          
                        }

                    }
                }
                form1DT_re = form1DT_re.DefaultView.ToTable(true);
                form1._dgv.DataSource = form1DT_re;
                
            }
        }
        #endregion 

 

'Language > C#' 카테고리의 다른 글

[c#]treelistview 노드코드  (0) 2020.02.03
[C#] Datagridview 마지막 빈 행 지우기  (1) 2020.01.31
[C#] textbox keypress 이벤트  (0) 2020.01.30
[C#] LINQ 연습 1일  (0) 2020.01.30
[C#] DataTable max값을 포함한 row 조회  (0) 2020.01.21

방법 1.

<Main.cs>

  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
           
            commonfunction.Main_SearchTextBox(e.KeyChar);
        }

<CommonFuncation.class>

 String TestValue;
       
        #region //Main.cs의 검색기능 메소드
        /// <summary>
        /// Main.cs의 검색텍스트박스 keypressEvent를 받아와 처리해 주는 메소드
        /// </summary>
        /// <param name="TextBoxInputValue"> KeypressEvent로 textbox에 입력된 값 </param>
        public void Main_SearchTextBox(char TextBoxInputValue)
        {
        
            if(TextBoxInputValue == Convert.ToChar(8) && TestValue.Length>0)
            {
                Debug.WriteLine("backspace!");
                TestValue = TestValue.Substring(0, TestValue.Length - 1);
                Debug.WriteLine(TestValue);
            }
            else
            {
                TestValue += TextBoxInputValue;
                Debug.WriteLine("inputText :: " + TestValue);
            }

 

메인에서 텍스트 박스 입력하는 즉시 CommonFuncation.class의 TestValue에 저장하는 코드

substring을 이용하여 backspace 입력 시

출력할 범위를 0부터 TestValue.Length -1 까지 지정하여 다시 TestValue 변수에 저장한다.

 

 

 

* 오류 수정 - 한글입력 시 마지막글자 2번입력되는 현상

    String TestValue;
       
        #region //Main.cs의 검색기능 메소드
        /// <summary>
        /// Main.cs의 검색텍스트박스 keypressEvent를 받아와 처리해 주는 메소드
        /// </summary>
        /// <param name="TextBoxInputValue"> KeypressEvent로 textbox에 입력된 값 </param>
   public void Main_SearchTextBox(char TextBoxInputValue)
        {
        
            if(TextBoxInputValue == Convert.ToChar(8) && MainSearchResult.Length>0)
            {
                Debug.WriteLine("backspace!");
                MainSearchResult = MainSearchResult.Substring(0, MainSearchResult.Length - 1);
                Debug.WriteLine(MainSearchResult);
            }

            else
            {
                char[] last_char;
                if ( !string.IsNullOrEmpty(MainSearchResult)) {
                    last_char = MainSearchResult.ToCharArray();
                    tochararray_last = last_char[last_char.Length - 1];
                
                if (!(0xAC00 <= TextBoxInputValue && TextBoxInputValue <= 0xD7A3) || (0x3131 <= TextBoxInputValue && TextBoxInputValue <= 0x318E) && MainSearchResult.Length > 0) { 
                    if ((0xAC00 <= tochararray_last && tochararray_last <= 0xD7A3) || (0x3131 <= tochararray_last && tochararray_last <= 0x318E) ) { 
                    //
                        MainSearchResult = MainSearchResult.Substring(0, MainSearchResult.Length - 1);
                }
                }
                }
                MainSearchResult += TextBoxInputValue;
             
                Debug.WriteLine("inputText :: " + MainSearchResult);
            }



        }
        #endregion

 

 

방법2. Thread 사용

<Main.cs>

  private void Main_searchTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {

           //commonfunction.Main_SearchTextBox(Main_searchTextBox.Text);
           
            Thread trd = new Thread(() => commonfunction.Main_SearchTextBox(Main_searchTextBox.Text));
            trd.Start();

            // commonfunction.Main_SearchTextBox(e.KeyChar);

        }

<CommonFunction.class>

String MainSearchResult;

        #region //Main.cs의 검색기능 메소드
        /// <summary>
        /// Main.cs의 검색텍스트박스 keypressEvent를 받아와 처리해 주는 메소드
        /// </summary>
        /// <param name="TextBoxInputValue"> KeypressEvent로 textbox에 입력된 값 </param>
        public void Main_SearchTextBox(String TextBoxInputValue)
        {

                 MainSearchResult = TextBoxInputValue;

                Debug.WriteLine("inputText :: " + MainSearchResult);

        }
        #endregion 

+ Recent posts