0

I have a database with 28 columns. First column is code, second Name and the rest are values.

public void displayData()
{
    con.Open();
    MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM gehaltes", con);
    DataTable dt = new DataTable();

    da.Fill(dt);
    dataGridView1.DataSource = dt;
    dataGridView1.AutoResizeColumn(DataGridViewAutoSizeColumnsMode.DisplayedCells);
    con.Close();
}

With this part of the program I see all the columns in the datagridview. I only want the first 2 but I have to use all the 28 columns if I want to make changes.

3
  • 3
    Maybe dont use SELECT * ?? Generally a good idea to always specify the columns in the order you want. You dont need all the columns to make changes unless you will be changing something in those other 26 column; which seems less likely if the user cant see/edit them Commented Jan 11, 2017 at 17:21
  • @Plutonix I think he means he doesn't want them displayed in the datagridview. Commented Jan 11, 2017 at 17:21
  • 2
    You should be able to loop over the datagridview's columns and set their visible properties. Commented Jan 11, 2017 at 17:22

2 Answers 2

1

You can set the visible property of individual columns:

DataGridView dgv;
// ...
foreach(DataGridViewColumn c in dgv.Columns)
   c.Visible = c.Name == "code" || c.Name == "Name";
Sign up to request clarification or add additional context in comments.

Comments

1

Set the AutoGenerateColumns property of the DataGridView to false, and add two columns with the property DataPropertyName refering to the names that you want to display.

Example:

da.Fill(dt);
dataGridView1.AutoGenerateColumns = false;

DataGridViewColumn col = new DataGridViewColumn();
col.Name = "name";
col.HeaderText = "header";
col.DataPropertyName = "yourDBField";

dataGridView1.Columns.Add(col);

dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumn(DataGridViewAutoSizeColumnsMode.DisplayedCells);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.