Darth Sucuk
Darth Sucuk

Reputation: 254

How to split string and write them in different row in same datagridview c#

I have a database which include my computer's ids,users,old users etc.I fill my dataview perfectly.In my db I have a olduser column and it's look like ;

john;marry;tonny

And my other column "date" looks like ;

02.10.2018;05.09.2017;30.08.2015 

So I want to see my datagridview like

PCNAME      ID     USER      OLDUSER     PLACE     DATE
computer1   1      herry                 spain   
computer1   1                 john       spain    02.10.2018
computer1   1                 marry      spain    05.09.2017
computer1   1                 tonny      spain    30.08.2015 

When I write the code below it always give me

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

error

 int i = 0;


 public void firstdatagrid()
    {
            DataTable table = new DataTable();
            dataGridView1.DataSource = table;
            baglantı = new SqlConnection();
            baglantı.ConnectionString = "Server=asdas;Database=asdsa;User Id=asdsa;password=asdaassad";
            baglantı.Open();

            komut = new SqlDataAdapter("SELECT * FROM TABLE WHERE PCID= '" + pcidcmbx.Text + "'", baglantı);
            ds = new System.Data.DataSet();
            komut.Fill(ds, "TABLE");
            dataGridView2.DataSource = ds.Tables[0];
            dataGridView2.Columns[0].HeaderText = "PCNAME";
            dataGridView2.Columns[1].HeaderText = "ID";
            dataGridView2.Columns[2].HeaderText = "USER";
            dataGridView2.Columns[3].HeaderText = "OLD USER";
            dataGridView2.Columns[4].HeaderText = "PLACE";
            dataGridView2.Columns[5].HeaderText = "DATE";

            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                names += row.Cells[3].Value;
                dates += row.Cells[5].Value;
                dataGridView2.Rows[0].Cells[3].Value = "";
                dataGridView2.Rows[0].Cells[5].Value = "";
            }

            foreach (var a in names.Split(new char[] { ';' }))
            {
                MessageBox.Show(a.ToString());
                DataRow newRow = table.NewRow();
                table.Rows.Add(newRow);
                dataGridView2.Rows[i].Cells[3].Value = a.ToString();
                i = i + 1;
            }
}

Upvotes: 2

Views: 687

Answers (1)

Nuisance
Nuisance

Reputation: 455

First of all you get this message because your values comes from db and when you try to add a new row manually,datagridview doesn't know what is come.

 DataTable table = new DataTable();
 DataGridView1.DataSource = table;

So try to use it will fix your problem I guess

DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);

Upvotes: 2

Related Questions