*VBNET String 을 Byte 로 Byte 를 String 으로 String <-> Char 변환 예제...
Main
- 사용한 컨트롤: Button 3개, TextBox 1개
전체 소스 코드
Form1.vb
Public Class Form1
Dim a As String = "ㄱㄴㄷ123abc"
Dim bb As Byte() = Nothing
Dim bc As Byte() = Nothing
Dim bd As Byte() = Nothing
Dim be As Byte() = Nothing
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
'String => Byte
bb = System.Text.Encoding.Default.GetBytes(a)
bc = System.Text.Encoding.Unicode.GetBytes(a)
bd = System.Text.Encoding.UTF8.GetBytes(a)
be = System.Text.Encoding.ASCII.GetBytes(a)
textBox1.Text = "String -> Byte 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "길이 " + System.Environment.NewLine
textBox1.Text += "Default: " + bb.Length.ToString() + System.Environment.NewLine
textBox1.Text += "Unicode: " + bc.Length.ToString() + System.Environment.NewLine
textBox1.Text += "UTF8: " + bd.Length.ToString() + System.Environment.NewLine
textBox1.Text += "ASCII: " + be.Length.ToString() + System.Environment.NewLine
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
'Byte => String
'바이트 배열에 아무것도 없으면...
If (bb Is Nothing) And (bc Is Nothing) And (bd Is Nothing) And (be Is Nothing) Then
MessageBox.Show("String -> Byte 변환 버튼 클릭 후 이용해 주세요.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Return
End If
textBox1.Text += "Byte -> String 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "Default: " + System.Text.Encoding.Default.GetString(bb) + System.Environment.NewLine
textBox1.Text += "Unicode: " + System.Text.Encoding.Unicode.GetString(bc) + System.Environment.NewLine
textBox1.Text += "UTF8: " + System.Text.Encoding.UTF8.GetString(bd) + System.Environment.NewLine
textBox1.Text += "ASCII: " + System.Text.Encoding.ASCII.GetString(be) + System.Environment.NewLine '<- 한글 깨짐 한글 유니코드 변환X
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
Private Sub button3_Click(sender As Object, e As EventArgs) Handles button3.Click
'String <=> Char
Dim sTmp As String = "가나다123abc"
Dim cTmp As Char() = sTmp.ToCharArray()
textBox1.Text += "String -> Char 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "Char 길이: -> " + cTmp.Length.ToString() + System.Environment.NewLine
textBox1.Text += "Char -> String 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "변환: " + New String(cTmp) + System.Environment.NewLine
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
End Class
* VBNET Listview Column Auto Size (컬럼 사이즈 자동) 예제...
-사용한 컨트롤: Listview 1개
전체 소스 코드
Form1.vb
Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
'예제 데이터 삽입...
For i As Integer = 0 To 9
Dim lvi As ListViewItem = New ListViewItem()
lvi.Text = (i + 1).ToString()
lvi.SubItems.Add("TEST " + (i + 1).ToString())
listView1.Items.Add(lvi)
Next
''리스트 뷰 컬럼 Auto Size
''리스트 뷰 컬럼 얻어오기...
'listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
'Dim cc As ListView.ColumnHeaderCollection = listView1.Columns
'For j As Integer = 0 To cc.Count - 1
' Dim iColWidth As Integer = TextRenderer.MeasureText(cc(j).Text, listView1.Font).Width + 10
' '대입
' If iColWidth > cc(j).Width Then
' cc(j).Width = iColWidth
' End If
'Next
End Sub
End Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CSharp_ListViewColumnsAuto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//예제 데이터 삽입...
for (int i = 0; i < 10; i++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = (i + 1).ToString();
lvi.SubItems.Add("TEST " + (i + 1).ToString());
listView1.Items.Add(lvi);
}
//리스트뷰 컬럼 Auto Size
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
ListView.ColumnHeaderCollection cc = listView1.Columns;
for (int i = 0; i < cc.Count; i++)
{
int colWidth = TextRenderer.MeasureText(cc[i].Text, listView1.Font).Width + 10;
if (colWidth > cc[i].Width)
{
cc[i].Width = colWidth;
}
}
}
}
}
Imports System.Net.Json
Imports System.Net
Imports System.IO
Public Class Form1
Dim iCount As Integer = 0
Dim ltResult As List(Of Integer) = New List(Of Integer)()
Private Function IsNullString(ByVal str As String) As Boolean
Return String.IsNullOrEmpty(str)
End Function
Private Function IsInt(ByVal ob As Object) As Integer
If ob Is Nothing Then
Return 0
End If
Dim iCheck As Integer = 0
Dim bCheck As Boolean = Integer.TryParse(ob.ToString(), iCheck)
If Not bCheck Then
Return 0
End If
Return iCheck
End Function
Private Function IsCheck() As Boolean
'문자열 체크.
If IsNullString(TextBox1.Text) And _
IsNullString(TextBox2.Text) And _
IsNullString(TextBox3.Text) And _
IsNullString(TextBox4.Text) And _
IsNullString(TextBox5.Text) And _
IsNullString(TextBox6.Text) Then
MessageBox.Show("빈 값일 순 없습니다.")
Return False
End If
'숫자 체크...
If IsInt(TextBox1.Text) And _
IsInt(TextBox2.Text) And _
IsInt(TextBox3.Text) And _
IsInt(TextBox4.Text) And _
IsInt(TextBox5.Text) And _
IsInt(TextBox6.Text) Then
MessageBox.Show("숫자만 입력 해 주세요.")
Return False
End If
'회차 번호 체크...
If IsInt(TextBox8.Text) = 0 And IsNullString(TextBox8.Text) Then
MessageBox.Show("숫자만 입력 또는 빈 값일 순 없습니다.")
TextBox8.Text = ""
TextBox8.Focus()
Return False
End If
Return True
End Function
Private Function GetHttpLottoString(ByVal strUri As String) As String
Dim strResponseText As String = String.Empty
Dim request As HttpWebRequest = CType(WebRequest.Create(strUri), HttpWebRequest)
request.Method = "GET"
'웹리퀘스트 타임아웃
request.Timeout = 20 * 1000 ' 20초
'request.Headers.Add("Authorization", "BASIC SGVsbG8="); // 헤더 추가 방법
'응답 받기
Using hwr As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
'응답이 정상적으로 이루어 졌으면...
If hwr.StatusCode = HttpStatusCode.OK Then
Dim respStream As Stream = hwr.GetResponseStream()
Using sr As StreamReader = New StreamReader(respStream)
strResponseText = sr.ReadToEnd()
End Using
Else
strResponseText = ""
End If
End Using
Return strResponseText
End Function
Private Sub Check_Result(ByVal iNumber As Integer)
'-2 한 값은 마집막 보너스 넘버는 체크 안함...
For i As Integer = 0 To ltResult.Count - 2
If iNumber = ltResult(i) Then
iCount = iCount + 1
Return
End If
Next
End Sub
Private Sub MessageResult(ByVal iBonus As Integer)
Select Case iCount
Case 6
lblResult.Text = "축하 드립니다. 1등에 당첨 되셨습니다."
Case 5
If iBonus = 1 Then
lblResult.Text = "축하 드립니다. 2등에 당첨 되셨습니다."
Else
lblResult.Text = "축하 드립니다. 3등에 당첨 되셨습니다."
End If
Case 4
lblResult.Text = "축하 드립니다. 4등에 당첨 되셨습니다."
Case 3
lblResult.Text = "축하 드립니다. 5등에 당첨 되셨습니다."
Case Else
lblResult.Text = "꽝 입니다. 다음 기회에...반드시 성공을..."
End Select
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ltLottoNumber As List(Of Integer) = New List(Of Integer)
Dim iBonus As Integer = 0
'초기화...
ltResult.Clear()
iCount = 0
'텍스트 박스들 체크...
If Not IsCheck() Then
Return
End If
ltLottoNumber.Add(Convert.ToInt32(TextBox1.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox2.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox3.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox4.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox5.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox6.Text.Trim()))
'로또 회차 넘버 불러오기...
Dim strReturnValue As String = GetHttpLottoString("https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=" + TextBox8.Text)
If strReturnValue = "" Then
MessageBox.Show("Lotto Number 불러오기 실패...")
Return
End If
'json 파싱
Dim jtr As Json.JsonTextParser = New Json.JsonTextParser()
Dim jo As Json.JsonObject = jtr.Parse(strReturnValue)
Dim jac As Json.JsonObjectCollection = jo
'불러오기가 성공 하면...
If jac("returnValue").GetValue().ToString() = "success" Then
ltResult.Add(Convert.ToInt32(jac("drwtNo1").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo2").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo3").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo4").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo5").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo6").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("bnusNo").GetValue().ToString().Trim()))
TextBox7.Text = jac("bnusNo").GetValue().ToString().Trim()
End If
'Check Result
For i As Integer = 0 To ltLottoNumber.Count - 1
Check_Result(ltLottoNumber(i))
If ltLottoNumber(i) = ltResult(ltResult.Count - 1) Then
iBonus = 1
End If
MessageResult(iBonus)
Next
End Sub
Private Sub TextBox8_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox8.KeyDown
If e.KeyCode = Keys.Enter Then
Button1_Click(Nothing, Nothing)
End If
End Sub
End Class
* VBNET 랜덤(Random) 클래스를 이용한 간단한 로또(Lotto) 숫자 생성 예제...
- 사용한 컨트롤 : Button 1개, Label 1개, TextBox 1개
전체 소스 코드
Form1.vb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = Create_LottoNumber()
End Sub
Private Function Create_LottoNumber() As String
Dim strTmp As String = ""
Dim strNumber As String = ""
Dim strBonusNumber As String = ""
Dim imsiNum(7) As Integer
For i As Integer = 0 To 6
Dim rnd As Random = New Random()
Dim bCheck As Boolean = False
imsiNum(i) = rnd.Next(1, 45)
For j As Integer = 0 To i - 1
'같은 번호 이면... 다시
If imsiNum(i) = imsiNum(j) Then
i = i - 1
bCheck = True
End If
Next
'문자열로 합치기
If Not bCheck Then strTmp += imsiNum(i).ToString() + ", "
Next
'Lotto Number 만 가려내기
strNumber = strTmp.Substring(0, strTmp.LastIndexOf(",") - 3)
'마지막 , 제거
strNumber = strNumber.Substring(0, strNumber.LastIndexOf(","))
'보너스 번호 가져 오기
strBonusNumber = strTmp.Substring(strTmp.LastIndexOf(",") - 5, 2).Trim()
strBonusNumber = strBonusNumber.Substring(0, strBonusNumber.LastIndexOf(","))
Return "LottoNumber : " + strNumber + " BonusNumber : " + strBonusNumber
End Function
End Class