반응형

C# -- listbox 에서 선택해제하기 (deselect)



참고 : https://truepia.tistory.com/99



TextBox 의 autocomplete 를 직접 구현하기위해 코딩중에...

ListBox 에서 선택해제(deselect)를 해야 하는 상황 발생함.



this.listBox1.SelectionMode = SelectionMode.None;


을 사용할수 있지만, 그러면 화면깜박임 발생하는 경우있음.



그리고, 그냥 


this.listBox1.SelectedIndex = -1;


을 입력하면, 선택해제가 안됨...



열심히 구글링하다가..  위의 참고 블러그 찾아서..

변형하여 해결함.



< 해결책 >

            this.listBox1.BeginInvoke(new Action(() =>

            {

                //this.listBox1.SelectedItem = null;

                this.listBox1.SelectedIndex = -1;

            }));






< 실행화면 >




< 소스 >


using System;
using System.Windows.Forms;
namespace listbox_deselect
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.listBox1.Items.Add(1);
this.listBox1.Items.Add(2);
this.listBox1.Items.Add(566);
this.listBox1.Items.Add("test");
this.listBox1.Items.Add(5);
this.listBox1.Items.Add(337);
this.listBox1.Items.Add(64);
this.listBox1.Items.Add(7);
}
private void buttonSelect_Click(object sender, EventArgs e)
{
//this.listBox1.SelectionMode = SelectionMode.One;
this.listBox1.SelectedIndex = 2;
}
private void buttonDeselect_Click(object sender, EventArgs e)
{
//this.listBox1.SelectionMode = SelectionMode.None;
//this.listBox1.SelectedItem = null;
//this.listBox1.SelectedIndex = -1;
this.listBox1.BeginInvoke(new Action(() =>
{
//this.listBox1.SelectedItem = null;
this.listBox1.SelectedIndex = -1;
}));
}
}
}



반응형
Posted by 자유프로그램
,

C# -- base64 인코딩

C# 2020. 7. 25. 10:42
반응형

base64 인코딩



참고 : https://www.youtube.com/watch?v=9oeAoWPXtUg&list=PLlsKgYi2Lw722PMqESdivKJQgRtJAdbzn&index=23


        https://www.base64decode.org/  ==> 온라인 base 인코딩, 디코딩 확인 사이트



C# 에서 string 문자열을 utf8 용 base64 인코딩 문자열로 바꾸는 함수 만들자..




< 소스 >


using System;
using System.Text;
namespace Test
{
public class Base64Converter
{
public static string GetUTF8Base64String(string username, string password)
{
string txt = username + ":" + password;
byte[] bytesUTF8 = Encoding.UTF8.GetBytes(txt); // txt 문자열의 UTF8 인코딩에 해당하는 byte 배열 구함.
//byte[] bytesUnicode = Encoding.Unicode.GetBytes(txt);
//foreach(var x in bytesUTF8)
//{
// Console.Write($"{x} ");
//}
//Console.WriteLine();
//foreach (var x in bytesUnicode)
//{
// Console.Write($"{x} ");
//}
//Console.WriteLine();
string base64UTF8 = Convert.ToBase64String(bytesUTF8);
//string base64Unicode = Convert.ToBase64String(bytesUnicode);
//Console.WriteLine($" base64UTF8 ==> {base64UTF8}");
//Console.WriteLine($" base64Unicode ==> {base64Unicode}");
return base64UTF8;
}
public static string GetUnicodeBase64String(string username, string password)
{
string txt = username + ":" + password;
byte[] bytesUnicode = Encoding.Unicode.GetBytes(txt); // txt 문자열의 Unicode 인코딩에 해당하는 byte 배열 구함.
//foreach (var x in bytesUnicode)
//{
// Console.Write($"{x} ");
//}
//Console.WriteLine();
string base64Unicode = Convert.ToBase64String(bytesUnicode);
//Console.WriteLine($" base64Unicode ==> {base64Unicode}");
return base64Unicode;
}
}
}




반응형
Posted by 자유프로그램
,
반응형

C# -- datagridview 에서 virtual mode 사용하기



참고 : https://docs.microsoft.com/ko-kr/dotnet/framework/winforms/controls/implementing-virtual-mode-wf-datagridview-control

           ---> row-level commit scope


        https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.forms.datagridview.virtualmode?view=netframework-4.8

          ---> cell-level commit scope


        https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/virtual-mode-in-the-windows-forms-datagridview-control




** VirtualMode 전용 event


   -- 읽기 전용인 경우는, CellValueNeeded event 만 사용하면 됨.





<< 실행 화면 1 -- row-level commit scope >>




<< 실행 화면 2 -- cell-level commit scope >>




<< 소스 1 -- row-level commit scope >>


using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataGridView_VirtalMode_test1
{
public partial class Form1 : Form
{
private DataGridView dataGridView1 = new DataGridView();
// Declare an ArrayList to serve as the data store.
private ArrayList customers = new ArrayList();
// Declare a Customer object to store data for a row being edited.
private Customer customerInEdit;
// Declare a variable to store the index of a row being edited.
// A value of -1 indicates that there is no row currently in edit.
private int rowInEdit = -1;
// Declare a variable to indicate the commit scope.
// Set this value to false to use cell-level commit scope.
private bool rowScopeCommit = true;
public Form1()
{
InitializeComponent();
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
//this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView virtual-mode demo (row-level commit scope)";
}
private void Form1_Load(object sender, EventArgs e)
{
// Enable virtual mode.
this.dataGridView1.VirtualMode = true;
// Connect the virtual-mode events to event handlers.
this.dataGridView1.CellValueNeeded += new
DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
this.dataGridView1.CellValuePushed += new
DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
this.dataGridView1.NewRowNeeded += new
DataGridViewRowEventHandler(dataGridView1_NewRowNeeded);
this.dataGridView1.RowValidated += new
DataGridViewCellEventHandler(dataGridView1_RowValidated);
this.dataGridView1.RowDirtyStateNeeded += new
QuestionEventHandler(dataGridView1_RowDirtyStateNeeded);
this.dataGridView1.CancelRowEdit += new
QuestionEventHandler(dataGridView1_CancelRowEdit);
this.dataGridView1.UserDeletingRow += new
DataGridViewRowCancelEventHandler(dataGridView1_UserDeletingRow);
// Add columns to the DataGridView.
DataGridViewTextBoxColumn companyNameColumn = new
DataGridViewTextBoxColumn();
companyNameColumn.HeaderText = "Company Name";
companyNameColumn.Name = "Company Name";
DataGridViewTextBoxColumn contactNameColumn = new
DataGridViewTextBoxColumn();
contactNameColumn.HeaderText = "Contact Name";
contactNameColumn.Name = "Contact Name";
this.dataGridView1.Columns.Add(companyNameColumn);
this.dataGridView1.Columns.Add(contactNameColumn);
this.dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
// Add some sample entries to the data store.
this.customers.Add(new Customer(
"Bon app'", "Laurence Lebihan"));
this.customers.Add(new Customer(
"Bottom-Dollar Markets", "Elizabeth Lincoln"));
this.customers.Add(new Customer(
"B's Beverages", "Victoria Ashworth"));
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 4;
}
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
if (e.Row.Index < this.customers.Count)
{
// If the user has deleted an existing row, remove the
// corresponding Customer object from the data store.
this.customers.RemoveAt(e.Row.Index);
}
if (e.Row.Index == this.rowInEdit)
{
// If the user has deleted a newly created row, release
// the corresponding Customer object.
this.rowInEdit = -1;
this.customerInEdit = null;
}
}
private void dataGridView1_CancelRowEdit(object sender, QuestionEventArgs e)
{
if (this.rowInEdit == this.dataGridView1.Rows.Count - 2 && this.rowInEdit == this.customers.Count)
{
// If the user has canceled the edit of a newly created row,
// replace the corresponding Customer object with a new, empty one.
this.customerInEdit = new Customer();
}
else
{
// If the user has canceled the edit of an existing row,
// release the corresponding Customer object.
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_RowDirtyStateNeeded(object sender, QuestionEventArgs e)
{
if (!rowScopeCommit)
{
// In cell-level commit scope, indicate whether the value
// of the current cell has been modified.
e.Response = this.dataGridView1.IsCurrentCellDirty;
}
}
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
// Save row changes if any were made and release the edited
// Customer object if there is one.
if (e.RowIndex >= this.customers.Count &&
e.RowIndex != this.dataGridView1.Rows.Count - 1)
{
// Add the new Customer object to the data store.
this.customers.Add(this.customerInEdit);
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.customerInEdit != null &&
e.RowIndex < this.customers.Count)
{
// Save the modified Customer object in the data store.
this.customers[e.RowIndex] = this.customerInEdit;
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.dataGridView1.ContainsFocus)
{
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
{
// Create a new Customer object when the user edits
// the row for new records.
this.customerInEdit = new Customer();
this.rowInEdit = this.dataGridView1.Rows.Count - 1;
}
// 변경된 셀 값에 내부 데이터 원본의 스토리지가 필요할 때 발생
private void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
{
Customer customerTmp = null;
// Store a reference to the Customer object for the row being edited.
if (e.RowIndex < this.customers.Count)
{
// If the user is editing a new row, create a new Customer object.
this.customerInEdit = new Customer(
((Customer)this.customers[e.RowIndex]).CompanyName,
((Customer)this.customers[e.RowIndex]).ContactName);
customerTmp = this.customerInEdit;
this.rowInEdit = e.RowIndex;
}
else
{
customerTmp = this.customerInEdit;
}
// Set the appropriate Customer property to the cell value entered.
String newValue = e.Value as String;
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
customerTmp.CompanyName = newValue;
break;
case "Contact Name":
customerTmp.ContactName = newValue;
break;
}
}
// DataGridView에서 셀을 서식 지정하고 표시하기 위해 셀에 대한 값이 필요할 때 발생합니다.
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
// If this is the row for new records, no values are needed.
if (e.RowIndex == this.dataGridView1.RowCount - 1) return;
Customer customerTmp = null;
// Store a reference to the Customer object for the row being painted.
if (e.RowIndex == rowInEdit)
{
customerTmp = this.customerInEdit;
}
else
{
customerTmp = (Customer)this.customers[e.RowIndex];
}
// Set the cell value to paint using the Customer object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
e.Value = customerTmp.CompanyName;
break;
case "Contact Name":
e.Value = customerTmp.ContactName;
break;
}
}
}
public class Customer
{
private String companyNameValue;
private String contactNameValue;
public Customer()
{
// Leave fields empty.
}
public Customer(String companyName, String contactName)
{
companyNameValue = companyName;
contactNameValue = contactName;
}
public String CompanyName
{
get
{
return companyNameValue;
}
set
{
companyNameValue = value;
}
}
public String ContactName
{
get
{
return contactNameValue;
}
set
{
contactNameValue = value;
}
}
}
}



<< 소스 2 -- cell-level commit scope >>


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataGridView_VirtualMode_test3
{
public partial class Form1 : Form
{
DataGridView dataGridView1 = new DataGridView();
public Form1()
{
InitializeComponent();
Text = "DataGridView virtual-mode demo (cell-level commit scope)";
dataGridView1.NewRowNeeded +=
new DataGridViewRowEventHandler(dataGridView1_NewRowNeeded);
dataGridView1.RowsAdded +=
new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
dataGridView1.CellValidating +=
new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
dataGridView1.CellValueNeeded +=
new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
dataGridView1.CellValuePushed +=
new DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
Controls.Add(dataGridView1);
dataGridView1.VirtualMode = true;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.Columns.Add("Numbers", "Positive Numbers");
dataGridView1.Rows.AddCopies(0, initialSize);
}
bool newRowNeeded;
private void dataGridView1_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
{
newRowNeeded = true;
}
const int initialSize = 5000000;
int numberOfRows = initialSize;
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (newRowNeeded)
{
newRowNeeded = false;
numberOfRows = numberOfRows + 1;
}
}
#region "data store maintance"
const int initialValue = -1;
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
if (store.ContainsKey(e.RowIndex))
{
// Use the store if the e value has been modified
// and stored.
e.Value = store[e.RowIndex];
}
else if (newRowNeeded && e.RowIndex == numberOfRows)
{
if (dataGridView1.IsCurrentCellInEditMode)
{
e.Value = initialValue;
}
else
{
// Show a blank value if the cursor is just resting
// on the last row.
e.Value = String.Empty;
}
}
else
{
e.Value = e.RowIndex;
}
}
private void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
{
store.Add(e.RowIndex, int.Parse(e.Value.ToString()));
}
#endregion
private Dictionary<int, int> store = new Dictionary<int, int>();
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";
}
}
}
}




반응형
Posted by 자유프로그램
,
반응형

mssql -- database 생성후 접속 권한 부여하기


참고:  https://docs.microsoft.com/en-us/sql/relational-databases/lesson-1-connecting-to-the-database-engine?view=sql-server-ver15



** 발생 상황; 

  -- MS 에서 sample로 제공하는, NorthWind db 를 생성한후, C# 에서 접속하려고 했는데 접속이 안됨....




** 해결책

  -- MS SQL Server Management Studio 실행하여, Northwind 접속 가능한 로그인 추가함.

   




<< 순서 그림 >>





-- Windows 인증으로 진행함.







--> 다음으로 서버역할 을 선택하자.


-- 새로운 login 이 관리자 여야 하는 경우에는 . sysadmin 에도 체크 선택한다.

  그러지 않다면, public 에만 체크 된 상태로 놔둔다.



-- 마지막으로 '사용자매핑' 선택한후, 원하는 database 매핑 체크선택하고, 기본스키마 항목에 'dbd' 를 입력하고, 확인 버튼 누르면 끝.

   ; 사용자 항목은 자동으로 입력됨.




<< 완료후 모습 >>




** C# 에서 connection string 사용시,   sql 서버명을 그대로 모두 입력한후에야 정상 접속 성공함.

 


string strConn = @"Data Source=APT\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;";






반응형
Posted by 자유프로그램
,
반응형

visual studio 2017 에서 private github repository 만들기





<< Visual studio 2017 community 사용 화면 >>






<< github 에 생성된 repository 결과 >>








반응형
Posted by 자유프로그램
,