Reputation: 119
How can I pass substring or a single character within the datagridview.
this is my text file
qwqwqw
a000v00 5000x222w000
BB00fFF 444422555550
qwqwqw
i want to show this content in DataGridView in below format
1 2 3 4
a000 v00 5000x 222w000
BB00 fFF 44442 2555550
This is my error code How should I do ?
DataTable table = new DataTable();
table.Columns.Add("1", typeof(string));
table.Columns.Add("2", typeof(string));
table.Columns.Add("3", typeof(string));
table.Columns.Add("4", typeof(string));
string path;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
ofd.Title = "txt";
if (ofd.ShowDialog(this) == DialogResult.Cancel) return;
path = ofd.FileName;
string[] lines = File.ReadAllLines(path);
string[] values;
for (int i = 1; i < lines.Length-1; i++)
{
values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
table.Rows.Add(row);
}
private void Form1_Load(object sender, EventArgs e)
{
DataView.DataSource = table;
}
Thank you very much
Upvotes: 1
Views: 101
Reputation: 2282
Your split appears to only split into two items as only one space. Also you seem to be ignoring lines without a space separator.
If so, try chaning the code that parses the text line and creates the datatable to something like this:
for (int i = 1; i < lines.Length - 1; i++)
{
values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (values.Length == 2)
{
DataRow row = table.NewRow();
row[0] = values[0].Substring(0, 4);
row[1] = values[0].Substring(4).Trim();
row[2] = values[1].Substring(0, 5);
row[3] = values[1].Substring(5).Trim();
table.Rows.Add(row);
}
}
and make sure the table datasource of the datagridview.
Upvotes: 1