本文整理汇总了C#中System.Windows.Forms.DataGridView.AutoResizeColumns方法的典型用法代码示例。如果您正苦于以下问题:C# DataGridView.AutoResizeColumns方法的具体用法?C# DataGridView.AutoResizeColumns怎么用?C# DataGridView.AutoResizeColumns使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Windows.Forms.DataGridView
的用法示例。
在下文中一共展示了DataGridView.AutoResizeColumns方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DailyScheduleView
public static void DailyScheduleView(DataGridView view, MainForm mainForm)
{
if (view.DataSource == null)
{
return;
}
view.ColumnHeadersVisible = false;
view.RowHeadersVisible = false;
view.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
view.AutoResizeColumns();
view.AutoResizeRows();
view.AllowUserToResizeColumns = false;
view.AllowUserToResizeRows = false;
// LessonId
view.Columns[0].Visible = false;
view.Columns[0].Width = 0;
// Ring
view.Columns[1].Width = 56;
view.Columns[1].DefaultCellStyle.Font = new Font(view.DefaultCellStyle.Font.FontFamily, 14);
view.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
// LessonSummary
// view.Columns[2].Width = Percent(88, view.Width);
view.Columns[2].Width = view.Width - view.Columns[1].Width - 20;
}
示例2: IssuesView
public IssuesView(IDataProvider provider)
: base(provider.Master, "Issues")
{
Frame.Text = "Issues";
var result = new DataGridView
{
RowHeadersVisible = false,
SelectionMode = DataGridViewSelectionMode.RowHeaderSelect,
MultiSelect = true
};
var data = provider.Data.ToArray();
result.Columns.AddRange(DataGridViewColumns().ToArray());
result.Rows.AddRange(data.Select(CreateRow).ToArray());
result.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
result.CellClick += (a, b) => OnSelect(data[b.RowIndex], provider);
Client = result;
}
示例3: InitializeDataGridViewQuantitiveCharacteristic
private void InitializeDataGridViewQuantitiveCharacteristic(DataGridView _dataGridView)
{
_dataGridView.ColumnCount = 3;
_dataGridView.RowCount = 5;
_dataGridView.RowHeadersWidth = 50;
_dataGridView.Columns[0].Name = "Value";
_dataGridView.Columns[1].Name = "Standard deviation";
_dataGridView.Columns[2].Name = "Interval";
_dataGridView.Rows[0].HeaderCell.Value = "Average arithmetic mean";
_dataGridView.Rows[1].HeaderCell.Value = "Median";
_dataGridView.Rows[2].HeaderCell.Value = "Standard deviation";
_dataGridView.Rows[3].HeaderCell.Value = "Skewness";
_dataGridView.Rows[4].HeaderCell.Value = "Kurtosis";
_dataGridView.AutoResizeColumns();
_dataGridView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
}
示例4: format_dgv
void format_dgv(DataGridView dgv)
{
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
int headerW = dgv.RowHeadersWidth;
int columnsW = 0;
DataGridViewColumnCollection columns = dgv.Columns;
for (int i = 0; i < columns.Count; i++)
{
columnsW += columns[i].Width;
}
if (columnsW + headerW < dgv.Width)
{
int leftTotalWidht = dgv.Width - columnsW - headerW - 2;
int eachColumnAddedWidth = leftTotalWidht / columns.Count;
for (int i = 0; i < columns.Count; i++)
{
columns[i].Width += eachColumnAddedWidth;
}
}
}
示例5: filtrarDataGridView
public void filtrarDataGridView(DataGridView miDataGridView, String sqlQuery)
{
SqlDataAdapter adapter;
DataTable tabla;
try
{
adapter = new SqlDataAdapter(sqlQuery, Conexion.getConexion());
tabla = new DataTable();
adapter.Fill(tabla);
miDataGridView.DataSource = tabla;
miDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
adapter.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK);
}
}
示例6: ShowOnGridView
public static void ShowOnGridView(DataGridView dataGridView, String Query)
{
//Create a DataTable to hold the query results.
DataTable dTable = new DataTable();
//Fill the DataTable.
FillTable(Query, dTable);
//BindingSource to sync DataTable and DataGridView.
BindingSource bSource = new BindingSource();
//Set the BindingSource DataSource.
bSource.DataSource = dTable;
//Set the DataGridView DataSource.
dataGridView.DataSource = bSource;
dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
for (int i = 0; i < dataGridView.RowCount; i = i + 2)
{
dataGridView.Rows[i].DefaultCellStyle.BackColor = Color.AliceBlue;
dataGridView.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
}
for (int i = 1; i < dataGridView.RowCount; i = i + 2)
{
dataGridView.Rows[i].DefaultCellStyle.BackColor = Color.White;
dataGridView.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
}
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
}
示例7: DisplayRevisionData
/// <summary>
/// Generate a Windows modeless form on the fly
/// and display the revision data in it in a
/// DataGridView.
/// </summary>
void DisplayRevisionData(
List<RevisionData> revision_data,
IWin32Window owner)
{
System.Windows.Forms.Form form
= new System.Windows.Forms.Form();
form.Size = new Size( 680, 180 );
form.Text = "Revision Data";
DataGridView dg = new DataGridView();
dg.DataSource = revision_data;
dg.AllowUserToAddRows = false;
dg.AllowUserToDeleteRows = false;
dg.AllowUserToOrderColumns = true;
dg.Dock = System.Windows.Forms.DockStyle.Fill;
dg.Location = new System.Drawing.Point( 0, 0 );
dg.ReadOnly = true;
dg.TabIndex = 0;
dg.Parent = form;
dg.AutoSize = true;
dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dg.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCells );
dg.AutoResizeColumns();
//dg.Columns[2].AutoSizeMode
// = DataGridViewAutoSizeColumnMode.DisplayedCells;
//dg.Columns[3].AutoSizeMode
// = DataGridViewAutoSizeColumnMode.Fill;
form.ShowDialog( owner );
}
示例8: GetStats
private void GetStats(object state)
{
if (!CanConnect)
return;
try
{
DataSet dsViews = ExecuteSql(@"SELECT table_name FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='trafikverket' and table_type='VIEW' and table_name like 'Get%' order by table_name;");
var views = dsViews.Tables[0].Rows.Cast<DataRow>().Select(x => x.ItemArray[0]).ToArray();
//var views = "GetMaxMinAvgPerDay;GetMaxMinDiffPerMeasurePoint;GetMaxminAvgPerMonth".Split(';');
foreach (string view in views)
{
if (!flpViews.Controls.Cast<Control>().Any(c => c.Tag != null && c.Tag.ToString().Equals(view)))
{
DataGridView dgv = new DataGridView();
dgv.AutoGenerateColumns = true;
dgv.Name = "dgv" + view;
dgv.Tag = view;
dgv.Height = flpViews.Height - 10;
double dc = double.Parse(views.Count().ToString());
double w = (flpViews.Width / dc) - (dc * 3);
dgv.Width = int.Parse(Math.Floor(w).ToString());
using (DataSet ds = ExecuteSql("select * from trafikverket." + view + ";"))
this.Invoke((MethodInvoker)delegate
{
dgv.DataSource = ds.Tables[0];
flpViews.Controls.Add(dgv);
dgv.Refresh();
flpViews.Refresh();
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
});
}
else
{
DataGridView dgv = flpViews.Controls.Cast<Control>().FirstOrDefault(c => c.Tag != null && c.Tag.ToString().Equals(view)) as DataGridView;
if (dgv == null)
continue;
using (DataSet ds = ExecuteSql("select * from trafikverket." + view + ";"))
this.Invoke((MethodInvoker)delegate
{
dgv.DataSource = ds.Tables[0];
dgv.Refresh();
flpViews.Refresh();
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
});
}
}
}
catch { }
System.GC.Collect();
}
示例9: examinePredictionsToolStripMenuItem_Click
//.........这里部分代码省略.........
// only get point predictions in current slice if we've got a timeslice model
if (model is TimeSliceDCM)
pointPredictions = pointPredictions.Where(p => (p.Time.Ticks / (model as TimeSliceDCM).TimeSliceTicks) == timeSlice.Value).ToArray();
if (pointPredictions.Length > 0)
{
DataGridView dataView = new DataGridView();
dataView.ReadOnly = true;
dataView.AllowUserToAddRows = false;
int predictionIdCol = dataView.Columns.Add("prediction_id", "Prediction ID");
Dictionary<string, int> incidentProbCol = new Dictionary<string, int>();
Set<int> incidentCols = new Set<int>();
foreach (string incident in pointPredictions[0].IncidentScore.Keys)
{
string colName = "Threat: " + incident;
int incidentCol = dataView.Columns.Add(colName, colName);
incidentProbCol.Add(incident, incidentCol);
incidentCols.Add(incidentCol);
}
Dictionary<string, int> featureIdCol = new Dictionary<string, int>();
Set<int> featureCols = new Set<int>();
if (model is IFeatureBasedDCM)
{
IFeatureBasedDCM featureBasedModel = DisplayedPrediction.Model as IFeatureBasedDCM;
foreach (Feature feature in featureBasedModel.Features.OrderBy(f => f.Id))
{
string colName = "Feature: " + feature.ToString();
int featureCol = dataView.Columns.Add(colName, colName);
featureIdCol.Add(feature.Id, featureCol);
featureCols.Add(featureCol);
}
}
dataView.Rows.Add(pointPredictions.Length);
try
{
Set<string> logPointIdsToGet = new Set<string>(pointPredictions.Select(p => model.GetPointIdForLog(p.PointId, p.Time)).ToArray());
Dictionary<string, Tuple<List<Tuple<string, double>>, List<Tuple<string, string>>>> pointPredictionLog = model.ReadPointPredictionLog(DisplayedPrediction.PointPredictionLogPath, logPointIdsToGet);
for (int i = 0; i < pointPredictions.Length; ++i)
{
PointPrediction pointPrediction = pointPredictions[i];
dataView[predictionIdCol, i].Value = pointPrediction.PointId;
string logPointId = model.GetPointIdForLog(pointPrediction.PointId, pointPrediction.Time);
foreach (Tuple<string, double> labelConfidence in pointPredictionLog[logPointId].Item1)
if (labelConfidence.Item1 != PointPrediction.NullLabel)
dataView[incidentProbCol[labelConfidence.Item1], i].Value = labelConfidence.Item2;
foreach (Tuple<string, string> featureIdValue in pointPredictionLog[logPointId].Item2)
dataView[featureIdCol[featureIdValue.Item1], i].Value = featureIdValue.Item2;
}
}
catch (Exception ex) { Console.Out.WriteLine("Error while reading prediction log: " + ex.Message); }
dataView.SortCompare += new DataGridViewSortCompareEventHandler(delegate(object o, DataGridViewSortCompareEventArgs args)
{
int sortedColumn = args.Column.DisplayIndex;
if (args.CellValue1 == null && args.CellValue2 == null)
args.SortResult = args.RowIndex1.CompareTo(args.RowIndex2);
else if (args.CellValue1 == null || args.CellValue2 == null)
args.SortResult = args.CellValue1 == null ? -1 : 1;
else if (sortedColumn == predictionIdCol)
args.SortResult = ((int)args.CellValue1).CompareTo((int)args.CellValue2);
else if (incidentCols.Contains(sortedColumn))
args.SortResult = ((double)args.CellValue1).CompareTo((double)args.CellValue2);
else if (featureCols.Contains(sortedColumn))
{
double cellValue1, cellValue2;
if (double.TryParse(args.CellValue1.ToString(), out cellValue1) && double.TryParse(args.CellValue2.ToString(), out cellValue2))
args.SortResult = Math.Abs(cellValue1).CompareTo(Math.Abs(cellValue2));
else
args.SortResult = args.CellValue1.ToString().CompareTo(args.CellValue2.ToString());
}
else
throw new Exception("Unknown column type");
args.Handled = true;
});
PredictionDataGridViewForm form = new PredictionDataGridViewForm();
form.MaximumSize = Screen.FromControl(this).Bounds.Size;
form.Controls.Add(dataView);
form.Show();
dataView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
form.ClientSize = dataView.Size = dataView.PreferredSize;
form.Location = new System.Drawing.Point(0, 0);
}
else
MessageBox.Show("No predictions were made in that region.");
}
}
}
示例10: AutoResizeColumns
void AutoResizeColumns(DataGridView gridView)
{
try
{
gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
if (gridView.Columns.Count > 1 && Preferences.setLastColumnWidth &&
gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.lastColumnWidth)
{
// It seems that using 'MinimumWidth' instead of 'Width' prevents the DataGridView's NullReferenceExceptions
//gridView.Columns[gridView.Columns.Count - 1].Width = Preferences.lastColumnWidth;
gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.lastColumnWidth;
}
}
catch (NullReferenceException e)
{
// See https://connect.microsoft.com/VisualStudio/feedback/details/366943/autoresizecolumns-in-datagridview-throws-nullreferenceexception
// There are some rare situations with null ref exceptions when resizing columns and on filter finished
// So catch them here. Better than crashing.
Logger.logError("Error while resizing columns: " + e.Message);
Logger.logError(e.StackTrace);
}
}
示例11: UpdateTable
/// <summary>
/// Interactively update the database table by DataGridView and NpgsqlDataAdapter
/// Insert Update Delete
/// </summary>
private void UpdateTable(string strConn, string strSQL, NpgsqlParameter[] sqlParams, DataGridView gridView, out NpgsqlDataAdapter da, out DataSet ds)
{
ds = new DataSet();
da = this.GetDataAdapter(strConn, strSQL, sqlParams, false);
da.Fill(ds);
gridView.DataSource = ds.Tables[0];
gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
示例12: FormatDataGrid
private void FormatDataGrid(DataGridView grid)
{
var tbl = (DataTable)grid.DataSource;
var arasProxy = _proxy as ArasEditorProxy;
ArasMetadataProvider metadata = null;
if (arasProxy != null)
metadata = ArasMetadataProvider.Cached(arasProxy.Connection);
grid.Columns.Clear();
foreach (var dataCol in tbl.Columns.OfType<DataColumn>())
{
DataGridViewColumn col;
if (dataCol.DataType == typeof(bool))
{
col = new DataGridViewCheckBoxColumn();
}
else if (dataCol.DataType == typeof(DateTime))
{
col = new Controls.DataGridViewCalendarColumn();
}
else
{
var prop = dataCol.PropMetadata();
if (prop != null && metadata != null
&& string.Equals(prop.TypeName, "list", StringComparison.OrdinalIgnoreCase))
{
var combo = new DataGridViewListColumn();
combo.DisplayMember = "Label";
combo.ValueMember = "Value";
metadata.ListValues(prop.DataSource)
.Done(v => combo.DataSource = v.ToArray());
col = combo;
}
else
{
col = new DataGridViewTextBoxColumn();
}
}
col.DataPropertyName = dataCol.ColumnName;
col.ValueType = dataCol.DataType;
col.HeaderText = dataCol.Caption;
col.Visible = dataCol.IsUiVisible();
grid.Columns.Add(col);
}
grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader);
var minWidths = grid.Columns.OfType<DataGridViewColumn>().Select(c => c.Width).ToArray();
grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
var maxWidths = grid.Columns.OfType<DataGridViewColumn>().Select(c => c.Width).ToArray();
var maxWidth = (int)(grid.Width * 0.8);
//DataColumn boundColumn;
for (var i = 0; i < grid.Columns.Count; i++)
{
grid.Columns[i].Width = Math.Min(maxWidths[i] < 100 ? maxWidths[i] :
(maxWidths[i] < minWidths[i] + 60 ? maxWidths[i] : minWidths[i] + 60)
, maxWidth);
grid.Columns[i].DefaultCellStyle.Alignment =
(IsNumericType(grid.Columns[i].ValueType)
? DataGridViewContentAlignment.TopRight
: DataGridViewContentAlignment.TopLeft);
//boundColumn = ((DataTable)grid.DataSource).Columns[grid.Columns[i].DataPropertyName];
//grid.Columns[i].HeaderText = boundColumn.Caption;
//grid.Columns[i].Visible = boundColumn.IsUiVisible();
}
if (!grid.Columns.OfType<DataGridViewColumn>().Any(c => c.Visible))
{
foreach (var col in grid.Columns.OfType<DataGridViewColumn>())
{
col.Visible = true;
}
}
var orderedColumns = grid.Columns.OfType<DataGridViewColumn>()
.Select(c => new
{
Column = c,
SortOrder = GetSortOrder(c)
})
.OrderBy(c => c.SortOrder)
.ThenBy(c => c.Column.HeaderText)
.Select((c, i) => new { Column = c.Column, Index = i })
.ToArray();
foreach (var col in orderedColumns)
{
col.Column.DisplayIndex = col.Index;
}
grid.AllowUserToAddRows = _outputSet != null
&& ((DataTable)grid.DataSource).Columns.Contains("id")
&& ((DataTable)grid.DataSource).Columns.Contains(Extensions.AmlTable_TypeName);
grid.AllowUserToDeleteRows = grid.AllowUserToAddRows;
grid.ReadOnly = !grid.AllowUserToAddRows;
}
示例13: DisplayQueryData
private string DisplayQueryData(Connexion.Connexion connexion, string SQL, DataGridView dataGridViewOracleData, BackgroundWorker worker, DoWorkEventArgs eArgs)
{
string result = null;
try
{
//string SelectedTable = treeViewOracleSchema.SelectedNode.Text;
using (DbCommand cmd = connexion.Cnn.CreateCommand())
{
cmd.Transaction = connexion.MyTransaction;
int NumRec = 0;
try
{
string SQLCount = "SELECT count(*) " + SQL.Substring(SQL.ToUpper().IndexOf("FROM"));
cmd.CommandText = SQLCount; // string.Format("SELECT count(*) FROM {0}", SelectedTable);
cmd.Prepare();
NumRec = Convert.ToInt32(cmd.ExecuteScalar()) + dataGridViewOracleData.Rows.Count;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
NumRec = 0;
}
//string SQL = string.Format("SELECT * FROM {0}", SelectedTable);
cmd.CommandText = SQL;
cmd.Prepare();
//int colno = 0;
using (DbDataReader rd = cmd.ExecuteReader())
{
if (ClearData)
{
if (dataGridViewOracleData.InvokeRequired)
{
if (!worker.CancellationPending)
dataGridViewOracleData.Invoke(new datagridClear(ClearDataGrid));
}
else
{
dataGridViewOracleData.Rows.Clear();
dataGridViewOracleData.Columns.Clear();
}
for (int i = 0; i < rd.FieldCount && !worker.CancellationPending; i++)
{
if (dataGridViewOracleData.InvokeRequired)
{
dataGridViewOracleData.Invoke(new datagridAddCol(AddColDataGrid),
new object[] { rd.GetName(i), rd.GetName(i) });
}
else
dataGridViewOracleData.Columns.Add(rd.GetName(i), rd.GetName(i));
}
}
while (rd.Read() && !worker.CancellationPending)
{
DataGridViewRow dgrv = new DataGridViewRow();
for (int i = 0; i < dataGridViewOracleData.Columns.Count; i++)
{
dgrv.Cells.Add(new DataGridViewTextBoxCell());
dgrv.Cells[i].Value = rd.GetValue(i);
}
if (dataGridViewOracleData.InvokeRequired)
{
dataGridViewOracleData.Invoke(new datagridAddRow(AddRowDataGrid), new object[] { dgrv });
}
else
dataGridViewOracleData.Rows.Add(dgrv);
int CurrentNumRec = dataGridViewOracleData.Rows.Count;
if (worker.WorkerReportsProgress)
{
if (NumRec != 0)
{
int percentComplete = (int)((float)CurrentNumRec / (float)NumRec * 100);
worker.ReportProgress(percentComplete);
}
else
{
worker.ReportProgress(CurrentNumRec % 100);
}
}
}
if (worker.WorkerSupportsCancellation)
{
if (worker.CancellationPending)
{
eArgs.Cancel = true;
result = string.Format("Aborted by user. {0} records found", dataGridViewOracleData.Rows.Count);
}
else
{
result = string.Format("{0} records found", dataGridViewOracleData.Rows.Count);
}
}
if (dataGridViewOracleData.InvokeRequired)
{
dataGridViewOracleData.Invoke(new datagridAutoResizeColumns(DatagridAutoResizeColumns), new object[] { dataGridViewOracleData });
}
else
//.........这里部分代码省略.........
示例14: llenarDataGridView
public void llenarDataGridView(DataGridView dgv, String nombreTabla)
{
SqlDataAdapter adapter;
DataTable tabla;
try {
adapter = new SqlDataAdapter("select * from [THE_CVENGERS]." + nombreTabla, Conexion.getConexion());
tabla = new DataTable();
adapter.Fill(tabla);
dgv.DataSource=tabla;
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
adapter.Dispose();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
示例15: llenarDataGridViewDevolucion
public void llenarDataGridViewDevolucion(DataGridView dgv,String idCl)
{
SqlDataAdapter adapter;
DataTable tabla;
try
{
adapter = new SqlDataAdapter("select * from [THE_CVENGERS].comprasCliente("+idCl+") order by 'Fecha compra'", Conexion.getConexion());
tabla = new DataTable();
adapter.Fill(tabla);
dgv.DataSource = tabla;
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
adapter.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}