且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何拆分字符串并将其绑定到网格

更新时间:2022-12-12 16:52:02

您需要创建一个包含2个变量的类
1.一个int变量(a)
2.字符串变量(b)

然后,您需要维护此类的列表.假设类的名称为X.

List< x> valuesToBind = new List();

You need to create a class with 2 variables
1. An int variable (a)
2. A string variable (b)

Then you need to maintain a List of this class. Let''s say the name of class is X.

List<x> valuesToBind = new List();

string[] tildeSeperated = VALUEFROMDB.split('~');

foreach(string s in tildeSeperated)
{
    string[] temp = s.split(',');
    X objTemp = new X();
    objTemp.a= Convert.ToInt32(temp[0]);
    objTemp.b = temp[1];
    valuesToBind.Add(objTemp);
}
YOURDATAGRID.DataSource = valuesToBind;



请记住,以上代码既不是***实践,也不是经过测试的.我现在就在这里写了.因此,如果无法编译,则无法保证.仅仅是为了帮助您朝正确的方向发展.



Keep in mind that above code is neither the best practice or tested. I have written it right here right now. So no guarantees if it doesn''t compiles. It is just to help you in the right direction.




您只需要进行一些字符串操作即可.
为此,我解释了一个小例子.

Hi,

You just need to do some string manipulation...
for that I''ve explained a little example.

ArrayList List = new ArrayList();
            string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string[] SplittedString = TstStr.Split('~');
            foreach (string str in SplittedString)
            {
                string ConcatStr = "";
                string[] SubSplit = str.Trim().Split(',');
                foreach (string s in SubSplit)
                {
                    ConcatStr += s + " ";
                }
                List.Add(ConcatStr);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("data", typeof(string));                        
            dt.Columns.Add(dc);
            for (int i = 0; i < List.Count;i++ )
            {
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
            dataGridView1.DataSource = dt;




希望对您有帮助:)

快乐编码:)




Hope this help you:)

Happy Coding :)


在变体上可以使用LINQ.您可以使用如下查询:
And on variation could be to use LINQ. You could use a query like following:
string s1 = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";

var result = from item3 in
                (from item2 in
                    (from item1 in s1.Split('~') 
                     select item1)
                 select item2.Split(','))
             select new {
                field1 = item3[0],
                field2 = item3[1],
                field3 = item3[2]
             };


当然,有必要使用实型而不是匿名类型(...select new MyType {...),但这是一个示例,如果您想测试对您来说是否可行(使用调试器运行并查看其内容)结果在result:)).


Of course it would be necessary to use a real type instead of anonymous type (...select new MyType {...) but that''s an example if you want to test if it is feasible for you (run it using a debugger and see what''s the result in result :)).