C# 在datagridview列中拆分文本消息

C# 在datagridview列中拆分文本消息,c#,.net,datagridview,C#,.net,Datagridview,我已使tcpserver侦听器接收消息。例如,消息格式为:acc123 | 4723489237489234 我想在datagridview的列中按|拆分。第一条消息显示ok,但拆分后第二条消息返回以下错误:System.IndexOutOfRangeException:索引超出了数组的边界 以下是我目前的代码: void Timer1_Tick(object sender, EventArgs e) { string _acc = textFromClient3 ; strin

我已使tcpserver侦听器接收消息。例如,消息格式为:acc123 | 4723489237489234

我想在datagridview的列中按|拆分。第一条消息显示ok,但拆分后第二条消息返回以下错误:System.IndexOutOfRangeException:索引超出了数组的边界

以下是我目前的代码:

void Timer1_Tick(object sender, EventArgs e)
{
    string _acc = textFromClient3 ;
    string[] txt = _acc.Split(new[] {'|'}, StringSplitOptions.None);

    for (int row = 0; row < dataGridView1.Rows.Count; row++)
    {
        if (dataGridView1.Rows[row].Cells[0].Value != null &&
            dataGridView1.Rows[row].Cells[0].Value.Equals(textFromClient))
        {
            return;
        }
    }

    DataGridViewRow addRow = new DataGridViewRow();

    addRow.CreateCells(dataGridView1);
    addRow.Cells[0].Value = textFromClient;
    addRow.Cells[1].Value = txt[0];
    addRow.Cells[2].Value = txt[1];

    dataGridView1.Rows.Add(addRow);
}

其中textFromClient3是消息,文本[0]是acc123,文本[1]应该是我的示例中的4723489237489234。

我找到了解决方案

if (txt.Length > 1 && txt[1] != null)
    {
        addRow.Cells[2].Value = txt[1];
    }

谢谢大家的帮助。

也许我和你们有同样的问题。 但不同的是如何使用多行消息格式

"acc123|472348923|XXXXX"
"acc123|472348923|gggggggg"
"acc123|472348923|kkkkkkkk"
也许用这个可乐

for (i=0; i <txt.Length; i++)
if (txt.Length > 1 && txt[i] != null)
    {
        addRow.Cells[i].Value = txt[i];
    }

错误消息使我相信txt[1]没有被填充。您是否已在调试模式下检查txt[1]=4723489237489234?是否可以验证textFromClient3是否是您所期望的?另外,您是从尝试访问txt[1]还是从单元格[2]中得到该错误?textFromClient3正是我所期望的,错误来自txt[1]。我在单元格[2]上尝试了txt[0],效果良好。如果我在1个单元格中使用完整的textFromClient3,没有拆分,它也可以工作。@snowYetis它在调试模式下显示。找到了临时解决方案。我将COLLMN[2]设置为可调整大小并填充。现在可以工作了,但是如果texFromClient3是干净的,它仍然返回相同的错误。