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

来源:互联网 发布:测斜仪数据计算 编辑:程序博客网 时间:2024/04/30 17:54

JSON数组填充给Combox控件

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


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


作者:张建波 邮箱: 281451020@qq.com 电话: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();        }    }}


0 0
原创粉丝点击