C#中JSON数组填充给Combox控件

JSON数组填充给Combox控件

本系列文章由ex_net(张建波)编写,转载请注明出处。


http://blog.csdn.net/zjianbo/article/details/19699821


作者:张建波 邮箱: [email protected] 电话:13577062679 欢迎来电交流!


JSON字符串

{
    "sn": 1,
    "result": "Success",
    "data": [
        {
            "role_id": "1",
            "role_name": "超级管理员",
            "role_desc": ""
        },
        {
            "role_id": "2",
            "role_name": "管理员",
            "role_desc": ""
        },
        {
            "role_id": "3",
            "role_name": "财务",
            "role_desc": ""
        }
    ],
    "count": 3,
    "stamp": 1393070626
}

程序运行截图



C#关键代码

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 OPlatform
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //用 JSON库解析
            try
            {
                Newtonsoft.Json.Linq.JObject oC = Newtonsoft.Json.Linq.JObject.Parse(textBox3.Text);

              //  txtJsonResult.Text = oC["result"].ToString();
             //   txtJsonStamp.Text = oC["stamp"].ToString();
              //  Newtonsoft.Json.Linq.JObject data = oC["data"];
                Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)oC["data"];

                DataTable dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("Name");                                   

                for (var i = 0; i < ja.Count; i++)
                {
                    var tmpObj = (Newtonsoft.Json.Linq.JObject)ja[i];
                    var role_id = (string)tmpObj["role_id"];
                    var role_name = (string)tmpObj["role_name"];

                    DataRow dr = dt.NewRow();
                    dr["ID"] = role_id;
                    dr["Name"] = role_name;
                    dt.Rows.Add(dr);
                }


                comboBox1.DataSource = dt;
                comboBox1.DisplayMember = "Name";
                comboBox1.ValueMember = "ID";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            label2.Text = comboBox1.SelectedValue.ToString();
            label3.Text = comboBox1.SelectedText.ToString();
        }
    }
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。