'C# JSON 연동'에 해당되는 글 1건

728x90

C# comboBox 에 DB 테이블 정보를 가져와서 List Up 하는 방법이다.


MySQL DB를 직접 접속하는 방식이 아니라, Web 서버 정보를 JSON 으로 파싱해서 연동하는 방법이다.

기본 사항은 http://net-informations.com/q/faq/combovalue.html http://stackoverflow.com/questions/3063320/combobox-adding-text-and-value-to-an-item-no-binding-source 참조하면 도움된다.


코드는 일반적인 형태와 약간 다르게 처리할 수 밖에 없었다.

일반적인 경우에는 CB.DataSource = new BindingSource(cat1Source, null); 대신에 CB.DataSource = category1.result; 로 하면 된다.

하지만 이렇게 하면 전체 라는 구분자가 보이지 않는다.

그래서 별도로 Dictionary 를 이용해서 저장한 다음에 다시 매핑을 시켰다.

서버 파일을 변경하여 연동 에러가 발생하게 하여 미처 고려하지 못한 버그도 수정 반영하였다.

화면에 보이는 Text 만 고려하지 않고 value 까지 고려한 이유는 comboBox 아이템을 선택했을 때 uid 를 이용하여 DB 테이블 조회를 하기 위해서다.


using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Net;
using System.Windows.Forms;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Text;

private void Form1_Load(object sender, EventArgs e)
{
    cat1comboBox(cat1comboBox1); // DB 테이블 정보 가져오기
}

void cat1comboBox(ComboBox CB)
{
    CB.Items.Clear();
    Dictionary<string, string> cat1Source = new Dictionary<string, string>();
    cat1Source.Add("전체", "0");  // DB에는 전체가 없어서 추가
    try
    {
        string URL = "http://IP주소/cat1comboBox.php";
        string json = GetPHPJSON(URL);
        if (json != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            JsonHelper category1 = serializer.Deserialize<JsonHelper>(json); // Json String 객체로 반환 (역직렬화)

            foreach (var dr in category1.result)
            {
                cat1Source.Add(dr.classname, dr.uid);
            }

            CB.DataSource = new BindingSource(cat1Source, null);
            CB.DisplayMember = "Key";
            CB.ValueMember = "Value";

            CB.SelectedIndex = 0;  // 첫번째 아이템 선택
        }               
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
   
}

private void cat1comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
    if (cat1comboBox1.SelectedIndex > 0)
    {
        string key = ((KeyValuePair<string, string>)cat1comboBox1.SelectedItem).Key;
        string value = ((KeyValuePair<string, string>)cat1comboBox1.SelectedItem).Value;
        MessageBox.Show(key + " : " + value);
    }
}

string GetPHPJSON(string url)
{
    try
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(url);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
        {
            var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8, true);
            return @reader.ReadToEnd().Trim();
        }
        else
        {
            MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
            return null;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null;
    }
}


public class cat1comboBox
{
    public string uid { get; set; }
    public string classname { get; set; }      
}

public class JsonHelper
{
    public List<cat1comboBox> result { get; set; }
}

블로그 이미지

Link2Me

,