3

我创建了一个类库,并尝试将数据从 a 添加List<string[]>到 DataGridView。

字符串格式如下:

“测试,1^葡萄糖^10/24/2013 10:00;测试,2^BUN^10/25/2013 11:00;测试,3^BUN^10/25/2013 11:00”

我正在从另一个程序传递字符串。然后我将其列入列表,然后尝试将其添加到DataTable但没有这样的运气。我用四列创建了datagridview。

已选择 - 复选框

患者姓名 - 字符串

订单名称 - 字符串

订单日期 - 字符串

原因 - 组合框

我收到一个错误:

列表大于列数。

注意:我可以在传递给这个程序之前创建我想要的字符串,所以如果我需要在传递给程序之前对字符串做一些事情,请告诉我。有没有更简单的方法?

我只想显示数据,其余部分我会处理。

任何帮助,将不胜感激。

这是我的代码:

public partial class RenewOrders : Form
{
    public static string strMLMPatientData = string.Empty;

    public RenewOrders(string all_patient_data)
    {
        InitializeComponent();
        strMLMPatientData = "Test, 1^Glucose^10/24/2013 10:00;Test, 2^BUN^10/25/2013 11:00;Test, 3^BUN^10/25/2013 11:00"
    }

    private void RenewOrders_Load(object sender, EventArgs e)
    {    
        this.ConvertStringToList(strMLMPatientData);
    }

    private void ConvertStringToList(string strMLMPatientData)
    {
        var patient_list = strMLMPatientData.Split(';').Select(x => x.Split('^')).ToList();
        DataTable dtTable = ConvertListToDataTable(patient_list);
        dataGridView1.DataSource = dtTable;
    }

    // Convert to DataTable.
    static DataTable ConvertListToDataTable(List<string[]> patient_list)
    {
        // New table.
        DataTable dtTable = new DataTable();

        dtTable.Columns.Add("Name", typeof(string));
        dtTable.Columns.Add("Order Name", typeof(string));
        dtTable.Columns.Add("Order Date/Time", typeof(string));
        
        foreach (var row in patient_list)
        {
            table.Rows.Add(row);
        }

        return dtTable;
    }
}
4

1 回答 1

3

First you need to spit the string appropriately to get a list of string arrays. Something like this:

var patient_list = new List<string[]>(strMLMPatientData.Split(';').Select(x => x.Split(',')));

or even better:

var patient_list = strMLMPatientData.Split(';').Select(x => x.Split(',')).ToList();

You need Linq for that, but you get the idea.

Then you need to add columns to your data table. You cant add rows to it when there are no columns..

Try something like this in your function

//add columns appropriately
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Order", typeof(string));
table.Columns.Add("Date", typeof(string));
foreach (var row in patient_list)
    table.Rows.Add(row);

return table;

See an example here. As it stands, your comma separated input string doesnt seem to match your data table column structure. You need to work it out. But I hope you got the idea which way to go.

于 2013-06-15T20:37:29.473 回答