问题
How can i fill my datagridview with a - delimited text from my richtextbox?
example:
my richtextbox content:
000001-Kobe-Bryant-24-Lakers
000002-Lebron-James-23-Cavaliers
000003-Derick-Rose-1-Bulls
000004-Kevin-Durant-35-Thunders
Then the out put on my datafridview should be like this
PlayerID | Name | LastName | Number | Team |
-------------------------------------------------------------------
000001 |Kobe | Bryant | 24 |Lakers |
-------------------------------------------------------------------
000002 |Lebron | James | 23 |Cavaliers |
-------------------------------------------------------------------
000003 |Derick |Rose | 1 |Bulls |
-------------------------------------------------------------------
000004 |Kevin |Durant |35 |Thunders |
I cant put image thats why just draw a datagridview.
Here is the code that i am using
private void button2_Click(object sender, EventArgs e)
{
String delimitedText = richTextBox1.Text;
string[] holder = Regex.Split(richTextBox1.Text, "-");
// Populating into datagrid
dataGridView1.Rows[0].Cells[0].Value = holder[0].ToString();
dataGridView1.Rows[0].Cells[1].Value = holder[1].ToString();
dataGridView1.Rows[0].Cells[2].Value = holder[2].ToString();
dataGridView1.Rows[0].Cells[3].Value = holder[3].ToString();
dataGridView1.Rows[0].Cells[4].Value = holder[4].ToString();
}
it is just saving the first line.
Please someone help me with this.
回答1:
Use the C# Split option to get the delimited strings in an array and then populate it into a data grid.
Example:
String delimitedText = "000001-Kobe-Bryant-24-Lakers";
string[] stringObjects = delimitedText.Split('-');
// Populating into datagrid
dataGridView1.rows[0].cells[0] = stringObjects[0];
dataGridView1.rows[0].cells[1] = stringObjects[1];
dataGridView1.rows[0].cells[2] = stringObjects[2];
Thanks
回答2:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
String delimitedText = richTextBox1.Lines[i];
string[] holder = Regex.Split(delimitedText, "-");
// Populating into datagrid
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = holder[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = holder[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = holder[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = holder[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = holder[4].ToString();
}
}
来源:https://stackoverflow.com/questions/26232928/how-to-fill-datagridview-a-delimited-text-from-a-richtextbox