I have created a database and table using Visual Studio’s SQL Server Compact 3.5 with a dataset as my datasource. On my WinForm I have a DataGridView with 3 columns. However, I have been unable to figure out how to get the columns to take up the full width of the DataGridView which is shown in the image below.
I want to make the abbreviates column wider and then have the description column extend all the way over to the edge of the form. Any suggestions?
Update:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuickNote
{
public partial class hyperTextForm : Form
{
private static hyperTextForm instance;
public hyperTextForm()
{
InitializeComponent();
this.WindowState = FormWindowState.Normal;
this.MdiParent = Application.OpenForms.OfType<Form1>().First();
}
public static hyperTextForm GetInstance()
{
if (instance == null || instance.IsDisposed)
{
instance = new hyperTextForm();
}
return instance;
}
private void abbreviationsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.abbreviationsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.keywordDBDataSet);
}
private void hyperTextForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'keywordDBDataSet.abbreviations' table. You can move, or remove it, as needed.
this.abbreviationsTableAdapter.Fill(this.keywordDBDataSet.abbreviations);
abbreviationsDataGridView.Columns[1].Width = 60;
abbreviationsDataGridView.Columns[2].Width = abbreviationsDataGridView.Width - abbreviationsDataGridView.Columns[0].Width - abbreviationsDataGridView.Columns[1].Width - 72;
}
}
}
asked Aug 12, 2012 at 23:01
pallasmediapallasmedia
1,4594 gold badges25 silver badges56 bronze badges
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the «remainder» of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
answered Aug 13, 2012 at 0:09
hmqcnoesyhmqcnoesy
4,1153 gold badges30 silver badges47 bronze badges
6
Set the «AutoSizeColumnsMode» property to «Fill».. By default it is set to ‘NONE’. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.
DataGridView1.Columns[0].Width=100;// The id column
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining
//space
answered Aug 14, 2018 at 5:05
MShahid777MShahid777
711 silver badge4 bronze badges
In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode
property to None
.
ejuhjav
2,6002 gold badges24 silver badges31 bronze badges
answered May 4, 2020 at 7:19
I have created data grid view like this:
I want to change the column width. What should I do?
Should I change the code in designer.cs or just in .cs?
Update:
private void sqlConnStaff()
{
BindingSource dbBindSource = new BindingSource();
SqlCommand com;
com = new SqlCommand();
SqlConnection con = new SqlConnection(strCon);
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "view_staff";
SqlDataAdapter dataAdapter = new SqlDataAdapter(com);
IDCabang = new SqlParameter();
IDCabang.SqlDbType = SqlDbType.VarChar;
IDCabang.Size = 5;
IDCabang.ParameterName = "@IDCabang";
IDCabang.Value = IDCabangC;
IDCabang.Direction = ParameterDirection.Input;
com.Parameters.Add(IDCabang);
con.Open();
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dbBindSource.DataSource = table;
dataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
dataGridView3.ReadOnly = true;
// finally bind the data to the grid
dataGridView3.DataSource = dbBindSource;
con.Close();
}
asked May 14, 2013 at 10:13
noobprogrammernoobprogrammer
1,0807 gold badges22 silver badges35 bronze badges
You can set the Width property on the grid column like:
dataGridView1.Columns[0].Width = 200;
Or you can set the Width of the column in designer, modifying desinger.cs
is generally not recommended, instead go the Design View there modify the column width property.
If you are binding the resultset from code and creating the column as well from the (code based on the resultset) then you have to specify / modify the width in the code. If you are designing the grid in design view and adding column from there then define the width in Design view. Go to DataGrid properties, Columns -> Add new Column there modify the width:
answered May 14, 2013 at 10:16
HabibHabib
217k27 gold badges402 silver badges429 bronze badges
8
Check out DataGridViewColumn.Width
property.
Gets or sets the current width of the column.
DataGridViewColumn firstcolumn = dataGridView1.Columns[0];
column.Width = 150;
You can set your .Width
property as a pixel, default value is 100
.
You can change it if you want to use in Design View as Habib pointed.
answered May 14, 2013 at 10:21
Soner GönülSoner Gönül
96k102 gold badges205 silver badges356 bronze badges
0
You can change it in designer: click on DataGridView
then on this small arrow in upper right corner of gird and go Edit Columns -> Select Column -> Width
default is 100.
answered May 14, 2013 at 10:15
gzaxxgzaxx
17.1k2 gold badges36 silver badges54 bronze badges
Sorry i cant see the image. Is blocked by my work firewall but if you want to change the width i would advise never to modify the designer.cs
The designer.cs is auto generated code and people just assume this is not modified so it could become a pain in the ass to fix at a later date if needed.
Modify it in the .cs files.
answered May 14, 2013 at 10:18
CathalMFCathalMF
9,4955 gold badges66 silver badges100 bronze badges
I have created data grid view like this:
I want to change the column width. What should I do?
Should I change the code in designer.cs or just in .cs?
Update:
private void sqlConnStaff()
{
BindingSource dbBindSource = new BindingSource();
SqlCommand com;
com = new SqlCommand();
SqlConnection con = new SqlConnection(strCon);
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "view_staff";
SqlDataAdapter dataAdapter = new SqlDataAdapter(com);
IDCabang = new SqlParameter();
IDCabang.SqlDbType = SqlDbType.VarChar;
IDCabang.Size = 5;
IDCabang.ParameterName = "@IDCabang";
IDCabang.Value = IDCabangC;
IDCabang.Direction = ParameterDirection.Input;
com.Parameters.Add(IDCabang);
con.Open();
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dbBindSource.DataSource = table;
dataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
dataGridView3.ReadOnly = true;
// finally bind the data to the grid
dataGridView3.DataSource = dbBindSource;
con.Close();
}
asked May 14, 2013 at 10:13
noobprogrammernoobprogrammer
1,0807 gold badges22 silver badges35 bronze badges
You can set the Width property on the grid column like:
dataGridView1.Columns[0].Width = 200;
Or you can set the Width of the column in designer, modifying desinger.cs
is generally not recommended, instead go the Design View there modify the column width property.
If you are binding the resultset from code and creating the column as well from the (code based on the resultset) then you have to specify / modify the width in the code. If you are designing the grid in design view and adding column from there then define the width in Design view. Go to DataGrid properties, Columns -> Add new Column there modify the width:
answered May 14, 2013 at 10:16
HabibHabib
217k27 gold badges402 silver badges429 bronze badges
8
Check out DataGridViewColumn.Width
property.
Gets or sets the current width of the column.
DataGridViewColumn firstcolumn = dataGridView1.Columns[0];
column.Width = 150;
You can set your .Width
property as a pixel, default value is 100
.
You can change it if you want to use in Design View as Habib pointed.
answered May 14, 2013 at 10:21
Soner GönülSoner Gönül
96k102 gold badges205 silver badges356 bronze badges
0
You can change it in designer: click on DataGridView
then on this small arrow in upper right corner of gird and go Edit Columns -> Select Column -> Width
default is 100.
answered May 14, 2013 at 10:15
gzaxxgzaxx
17.1k2 gold badges36 silver badges54 bronze badges
Sorry i cant see the image. Is blocked by my work firewall but if you want to change the width i would advise never to modify the designer.cs
The designer.cs is auto generated code and people just assume this is not modified so it could become a pain in the ass to fix at a later date if needed.
Modify it in the .cs files.
answered May 14, 2013 at 10:18
CathalMFCathalMF
9,4955 gold badges66 silver badges100 bronze badges
- Remove From My Forums
-
Вопрос
-
Здравствуйте. Поскажите, как задать для каждого столбца определенную ширину?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim CONNECTION As New OleDbConnection( "Data Source=""C:UsersGeorgeekDesktopАвтошкола.mdb"";User ID=Admin;Provider=""Microsoft.Jet.OLEDB.4.0"";") CONNECTION.Open() Dim COMMAND As New System.Data.OleDb.OleDbCommand( "SELECT Курсанты.[Дата экзамена], Курсанты.[ФИО] As Курсант, Курсанты.[Адресс], Курсанты.[Телефон], Курсанты.[Откатанные часы], Инструктора.[ФИО] As Инструктор " & "FROM Инструктора INNER JOIN Курсанты ON Инструктора.id_инспектора = Курсанты.id_инспектора;", CONNECTION) Dim ADAPTER As New OleDbDataAdapter(COMMAND) Dim DATASET As New DataSet ADAPTER.Fill(DATASET, "Курсанты") DataGridView1.DataSource = DATASET DataGridView1.DataMember = "Курсанты" CONNECTION.Close() End Sub
-
Изменено
20 февраля 2011 г. 17:25
Подправил оформление
-
Изменено
Ответы
-
После заполнения таблицы можно выполнить что-то вроде:
DataGridView1.Columns(0).Width = 50 DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnsMode.Fill
либо обрабатывать событие
ColumnAdded (я бы выбрал этот вариант для простых или временных приложений), либо создать преднастроенные столбцы с заданным свойством Width в дизайнере и отключить автосоздание столбцов (я бы выбрал этот вариант в общем случае для всех остальных приложений).-
Предложено в качестве ответа
Naomi N
20 февраля 2011 г. 18:09 -
Помечено в качестве ответа
Abolmasov Dmitry
20 февраля 2011 г. 23:18
-
Предложено в качестве ответа
Жоржик 8 / 8 / 0 Регистрация: 20.02.2011 Сообщений: 31 |
||||
1 |
||||
20.02.2011, 20:49. Показов 53194. Ответов 9 Метки нет (Все метки)
Здравствуйте. Поскажите, как задать для каждого столбца определенную ширину?
__________________
2 |
galexser 125 / 125 / 8 Регистрация: 24.11.2010 Сообщений: 237 |
||||
20.02.2011, 21:36 |
2 |
|||
Решение
и повторяем так для каждого столбца
45 |
8 / 8 / 0 Регистрация: 20.02.2011 Сообщений: 31 |
|
20.02.2011, 22:01 [ТС] |
3 |
Спасибо
6 |
125 / 125 / 8 Регистрация: 24.11.2010 Сообщений: 237 |
|
21.02.2011, 05:36 |
4 |
Для спасибо на форуме есть кнопочка +1 в каждом ответете, если не трудно нажми ее
7 |
0 / 0 / 1 Регистрация: 31.10.2014 Сообщений: 45 |
|
25.01.2017, 08:26 |
5 |
galexser, Additional information: Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.
0 |
0 / 0 / 1 Регистрация: 31.10.2014 Сообщений: 45 |
|
01.02.2017, 01:32 |
6 |
Да кстати как решить эту проблему?
0 |
6 / 6 / 4 Регистрация: 20.10.2014 Сообщений: 392 |
|
01.02.2017, 14:09 |
7 |
у тя в таблице столбцов меньше чем ты пытаешься обратиться (у тя предположим 3 столбца, а ты обращаешься к 4 столбцу )
0 |
3353 / 1771 / 83 Регистрация: 05.08.2010 Сообщений: 4,471 |
|
01.02.2017, 14:39 |
8 |
Если что, в DataGridView нумерация коллекции Columns начинается с 0.
0 |
UAA1979 0 / 0 / 1 Регистрация: 31.10.2014 Сообщений: 45 |
||||
01.02.2017, 20:44 |
9 |
|||
А теперь вот так. Миниатюры
0 |
3353 / 1771 / 83 Регистрация: 05.08.2010 Сообщений: 4,471 |
|
01.02.2017, 22:50 |
10 |
Используйте try{} catch(){}, чтобы увидеть более точно где ошибка в коде. Но скорее всего не в том куске, который показали Вы..А где-то выше..
0 |