Example #1
0
        /// <summary>
        /// 列宽自适应模式
        /// </summary>
        /// <param name="DGV">表格名</param>
        /// <param name="bHeader">是否包含标题</param>
        public static void DGVAutoCol(DataGridView DGV, bool bHeader)
        {
            int width = 0;                              //定义一个局部变量,用于存储自动调整列宽以后整个DtaGridView的宽度

            for (int i = 0; i < DGV.Columns.Count; i++) //对于DataGridView的每一个列都调整
            {
                if (bHeader)
                {
                    DGV.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);//将每一列都调整为自动适应模式
                }
                else
                {
                    DGV.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader); //将每一列都调整为自动适应模式
                }
                width += DGV.Columns[i].Width;                                                    //记录整个DataGridView的宽度
            }
            if (width > DGV.Size.Width)                                                           //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度,则将DataGridView的列自动调整模式设置为显示的列即可,如果是小于原来设定的宽度,将模式改为填充。
            {
                DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
        }
Example #2
0
        /// <summary>
        /// 使DataGridView的列自适应宽度
        /// </summary>
        /// <param name="dgViewFiles"></param>
        public static void AutoSizeColumn(DataGridView dgViewFiles)
        {
            int width = 0;

            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgViewFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgViewFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度,
            //则将DataGridView的列自动调整模式设置为显示的列即可,
            //如果是小于原来设定的宽度,将模式改为填充。
            if (width > dgViewFiles.Size.Width)
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列 从左开始 0,1,2
            dgViewFiles.Columns[1].Frozen = false; //trun
        }
 static void ResizeGrid(DataGridView grid)
 {
     for (int i = 0; i < grid.ColumnCount; i++)
     {
         grid.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
     }
 }
Example #4
0
        void ColumnAutoFit()
        {
            int width = 0;

            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < _dgv.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                _dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += _dgv.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度,
            //则将DataGridView的列自动调整模式设置为显示的列即可,
            //如果是小于原来设定的宽度,将模式改为填充。
            if (width > _dgv.Size.Width)
            {
                _dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                _dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列 从左开始 0,1,2
            _dgv.Columns[1].Frozen = true;
        }
Example #5
0
        public static void AutoSizeColumn(DataGridView DGVFiles)
        {
            int width = 0;

            //使列自适应宽度
            //对于每一列都调整
            for (int i = 0; i < DGVFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                DGVFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个的宽度
                width += DGVFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度
            //则将每列都自动调整模式设置为显示的列即可
            //如果是小于原来设定的宽度,将模式改为填充
            if (width > DGVFiles.Size.Width)
            {
                DGVFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                DGVFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列从左开始
            DGVFiles.Columns[1].Frozen = true;
        }
        private void AutoSizeColumn(DataGridView dgViewFiles)
        {
            int width = 0;

            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgViewFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgViewFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度,
            //如果是小于原来设定的宽度,将模式改为填充。
            if (width > dgViewFiles.Size.Width)
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列 从左开始 0,1,2
            if (dgViewFiles.Rows.Count > 0)
            {
                dgViewFiles.Columns[0].Frozen = true;
            }
        }
Example #7
0
        private void dataGridView_DataSourceChanged(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            //DataTable dt = (DataTable)dgv.DataSource;
            if (dt == null)
            {
                return;
            }
            decimal[] tal = new decimal[dt.Columns.Count];
            if (dt.Columns.IndexOf(xh_field) < 0)
            {
                DataColumn dc = new DataColumn(xh_field, System.Type.GetType("System.Int32"));
                dt.Columns.Add(dc);

                dgv.Columns[xh_field].DisplayIndex = 0;
                dgv.Columns[xh_field].HeaderText   = "序号";

                dgv.Columns[xh_field].SortMode = DataGridViewColumnSortMode.Programmatic;
                dgv.AutoResizeColumn(dgv.Columns[xh_field].Index);

                dgv.Columns[xh_field].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgv.Columns[xh_field].Visible = true;
            }
            SumDataGridView(dgv);
        }
        private void AutoSizeColumn(DataGridView dgViewFiles)
        {
            try {
                int width = 0;
                //使列自使用宽度
                //对于DataGridView的每一个列都调整
                for (int i = 0; i < dgViewFiles.Columns.Count; i++)
                {
                    //将每一列都调整为自动适应模式
                    dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                    //记录整个DataGridView的宽度
                    width += dgViewFiles.Columns[i].Width;
                }
                //判断调整后的宽度与原来设定的宽度的关系,如果是调整后的宽度大于原来设定的宽度,
                //则将DataGridView的列自动调整模式设置为显示的列即可,
                //如果是小于原来设定的宽度,将模式改为填充。
                if (width > dgViewFiles.Size.Width)
                {
                    dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
                }
                else
                {
                    dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                }
                ////冻结某列 从左开始 0,1,2
                //dgViewFiles.Columns[1].Frozen = true;
                dgViewFiles.Columns[1].FillWeight = 1;
            }

            catch (Exception ex)
            {
                MessageBox.Show("系统发生异常,请联系管理员!", "错误");
                LogHelper.WriteLog("窗体异常", ex);
            }
        }
Example #9
0
        public static void AutoResizeFirstColumn(this DataGridView dgv)
        {
            dgv.AutoResizeColumn(columnIndex: 0);
            var col0 = dgv.Columns[0];

            col0.Width = Math.Max(col0.Width, col0.HeaderCell.Size.Width + SystemInformation.Border3DSize.Width);
        }
Example #10
0
 public static void ColAuto(DataGridView dGV)
 {
     for (int i = 0; i < dGV.Columns.Count; i++)                           //对于DataGridView的每一个列都调整
     {
         dGV.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells); //将每一列都调整为自动适应模式
     }
 }
Example #11
0
        private void AutoScaleControl(System.Windows.Forms.Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;

            float ctrlFontSize, hSize, wSize;

            //int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始
            foreach (System.Windows.Forms.Control c in ctl.Controls)
            { //**放在这里,是先缩放控件的子控件,后缩放控件本身
                //if (c.Controls.Count > 0)
                //   AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                ctrLeft0   = oldCtrl[ctrlNo].Left;
                ctrTop0    = oldCtrl[ctrlNo].Top;
                ctrWidth0  = oldCtrl[ctrlNo].Width;
                ctrHeight0 = oldCtrl[ctrlNo].Height;

                ctrlFontSize = oldCtrl[ctrlNo].Size;

                //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例
                //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;
                c.Left   = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                c.Top    = (int)((ctrTop0) * hScale);  //
                c.Width  = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                c.Height = (int)(ctrHeight0 * hScale); //

                wSize  = ctrlFontSize * wScale;
                hSize  = ctrlFontSize * hScale;
                c.Font = new Font(c.Font.Name, Math.Min(hSize, wSize), c.Font.Style, c.Font.Unit);

                ctrlNo++;//累加序号
                //**放在这里,是先缩放控件本身,后缩放控件的子控件
                if (c.Controls.Count > 0)
                {
                    AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                }
                if (ctl is DataGridView)
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);         // 自动调整列宽
                        widths += dgv.Columns[i].Width;                                           // 计算调整列后单元列的宽度和
                    }
                    if (widths >= ctl.Size.Width)                                                 // 如果调整列的宽度大于设定列宽
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 调整列的模式 自动
                    }
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;  // 如果小于 则填充
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
Example #12
0
        /// <summary>
        /// 改变控件位置、大小、字体大小
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="wScale">新旧窗体宽度的比例</param>
        /// <param name="hScale">新旧窗体的比例</param>
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            float sizeFont = wScale > hScale ? wScale : hScale;//字体变化倍数
            int   ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
            float ctrSizeFont0;

            foreach (Control c in ctl.Controls)
            {
                //**放在这里,是先缩放控件的子控件,后缩放控件本身
                //add by nicholas on 20171203 4 lines
                if (oldCtrl.Count == ctrlNo)
                {
                    break;
                }
                ctrLeft0     = oldCtrl[ctrlNo].Left;
                ctrTop0      = oldCtrl[ctrlNo].Top;
                ctrWidth0    = oldCtrl[ctrlNo].Width;
                ctrHeight0   = oldCtrl[ctrlNo].Height;
                ctrSizeFont0 = oldCtrl[ctrlNo].SizeFont;

                c.Left   = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                c.Top    = (int)((ctrTop0) * hScale);  //
                c.Width  = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                c.Height = (int)(ctrHeight0 * hScale);
                c.Font   = new Font(c.Font.FontFamily, ctrSizeFont0 * sizeFont);
                ctrlNo++; //累加序号
                          //**放在这里,是先缩放控件本身,后缩放控件的子控件
                if (c.Controls.Count > 0)
                {
                    AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                }

                //不同控件自适应修改
                if (ctl.GetType() == typeof(DataGridView))
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);         // 自动调整列宽
                        widths += dgv.Columns[i].Width;                                           // 计算调整列后单元列的宽度和
                    }
                    if (widths >= ctl.Size.Width)                                                 // 如果调整列的宽度大于设定列宽
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 调整列的模式 自动
                    }
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;  // 如果小于 则填充
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        public void ImportExcelData_Read(string fileName, DataGridView dgv)
        {
            // 엑셀 문서 내용 추출
            string connectionString = string.Empty;

            if (File.Exists(fileName))  // 파일 확장자 검사
            {
                if (Path.GetExtension(fileName).ToLower() == ".xls")
                {   // Microsoft.Jet.OLEDB.4.0 은 32 bit 에서만 동작되므로 빌드할 때 64비트로 하면 에러가 발생함.
                    connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0;", fileName);
                }
                else if (Path.GetExtension(fileName).ToLower() == ".xlsx")
                {
                    connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties=Excel 12.0;", fileName);
                }
                else if (Path.GetExtension(fileName).ToLower() == ".csv")
                {
                    connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0;", fileName);
                }
            }

            DataSet data = new DataSet();

            string          strQuery = "SELECT * FROM [Sheet1$]"; // 엑셀 시트명의 모든 데이터를 가져오기
            OleDbConnection oleConn  = new OleDbConnection(connectionString);

            oleConn.Open();

            OleDbCommand     oleCmd      = new OleDbCommand(strQuery, oleConn);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(oleCmd);

            DataTable dataTable = new DataTable();

            dataAdapter.Fill(dataTable);
            data.Tables.Add(dataTable);

            dgv.DataSource = data.Tables[0].DefaultView;

            // 데이터에 맞게 칼럼 사이즈 조정하기
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
            }
            dgv.AllowUserToAddRows = false;  // 빈레코드 표시 안하기
            dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
            //dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 화면크기에 맞춰 채우기

            dataTable.Dispose();
            dataAdapter.Dispose();
            oleCmd.Dispose();

            oleConn.Close();
            oleConn.Dispose();
        }
Example #14
0
        /// <summary>
        ///根据cell内容调整其宽度
        /// </summary>
        /// <param name="girdview">DataGridView</param>
        public static void AutoCellWidth(this DataGridView girdview)
        {
            int _columnSumWidth = 0;

            for (int i = 0; i < girdview.Columns.Count; i++)
            {
                girdview.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                _columnSumWidth += girdview.Columns[i].Width;
            }

            girdview.AutoSizeColumnsMode = _columnSumWidth > girdview.Size.Width ? DataGridViewAutoSizeColumnsMode.DisplayedCells : DataGridViewAutoSizeColumnsMode.Fill;
        }
Example #15
0
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;

            //int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始  
            foreach (Control c in ctl.Controls)
            {
                 //**放在这里,是先缩放控件的子控件,后缩放控件本身  
                //if (c.Controls.Count > 0)  
                //   AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用  
                             ctrLeft0 = oldCtrl[ctrlNo].Left;
                ctrTop0    = oldCtrl[ctrlNo].Top;
                ctrWidth0  = oldCtrl[ctrlNo].Width;
                ctrHeight0 = oldCtrl[ctrlNo].Height;
                //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例  
                //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;  
                c.Left   = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1  
                c.Top    = (int)((ctrTop0) * hScale);  //  
                c.Width  = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);  
                c.Height = (int)(ctrHeight0 * hScale); //  
                ctrlNo++;                              //累加序号  
                //**放在这里,是先缩放控件本身,后缩放控件的子控件  
                if (c.Controls.Count > 0)
                {
                    AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用  
                }
                if (ctl is DataGridView)
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);    // 自动调整列宽    
                            widths += dgv.Columns[i].Width;                                  // 计算调整列后单元列的宽度和                         
                    }
                    if (widths >= ctl.Size.Width)
                    {
                                                   // 如果调整列的宽度大于设定列宽    
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
                    }
                                                                                                   // 调整列的模式 自动    
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    }                                                                    // 如果小于 则填充    

                    Cursor.Current = Cursors.Default;
                }
            }
        }
Example #16
0
        private void autoReSize(Control superCtrl, float wideScale, float highScale)
        {
            int Left0, Top0, Width0, Height0;

            foreach (Control subCtrl in superCtrl.Controls)
            {
                //Get the origin infos of this components from list
                Left0   = compList[num].Left;
                Top0    = compList[num].Top;
                Width0  = compList[num].Width;
                Height0 = compList[num].Height;

                //Change the size
                subCtrl.Left   = (int)((Left0) * wideScale);
                subCtrl.Top    = (int)((Top0) * highScale);
                subCtrl.Width  = (int)(Width0 * wideScale);
                subCtrl.Height = (int)(Height0 * highScale);

                num++;

                //If have any sub components
                if (subCtrl.Controls.Count > 0)
                {
                    autoReSize(subCtrl, wideScale, highScale);
                }

                if (superCtrl is DataGridView)
                {
                    DataGridView dgv = superCtrl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                        widths += dgv.Columns[i].Width;
                    }

                    if (widths >= superCtrl.Size.Width)
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
                    }
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    }

                    Cursor.Current = Cursors.Default;
                }
            }
        }
Example #17
0
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;

            foreach (Control c in ctl.Controls)
            {
                int index = SearchRect(c.Name);
                if (index > 0 && index <= ctrlNo)
                {
                    ctrLeft0   = oldCtrl[index].Left;
                    ctrTop0    = oldCtrl[index].Top;
                    ctrWidth0  = oldCtrl[index].Width;
                    ctrHeight0 = oldCtrl[index].Height;
                    //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例
                    //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;
                    c.Left   = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                    c.Top    = (int)((ctrTop0) * hScale);  //
                    c.Width  = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                    c.Height = (int)(ctrHeight0 * hScale); //

                    //**放在这里,是先缩放控件本身,后缩放控件的子控件
                    if (c.Controls.Count > 0)
                    {
                        AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                    }
                    if (ctl is DataGridView)
                    {
                        DataGridView dgv = ctl as DataGridView;
                        Cursor.Current = Cursors.WaitCursor;

                        int widths = 0;
                        for (int i = 0; i < dgv.Columns.Count; i++)
                        {
                            dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);         // 自动调整列宽
                            widths += dgv.Columns[i].Width;                                           // 计算调整列后单元列的宽度和
                        }
                        if (widths >= ctl.Size.Width)                                                 // 如果调整列的宽度大于设定列宽
                        {
                            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 调整列的模式 自动
                        }
                        else
                        {
                            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;  // 如果小于 则填充
                        }
                        Cursor.Current = Cursors.Default;
                    }
                }
            }
        }
        // 구글링해서 찾은 소스인데 파일명 자동인식하는데
        // 문제는 원하는 파일명의 데이터가 아닌 다른 데이터가 출력될 수 있다는 점이 있어서 로직을 약간 보완했다.
        public void ReadExcel(string fileName, DataGridView dgv)
        {
            // 엑셀 문서 내용 추출
            object missing          = System.Reflection.Missing.Value;
            string connectionString = string.Empty;

            if (File.Exists(fileName))
            {
                if (Path.GetExtension(fileName).ToLower() == ".xls")
                {
                    // Microsoft.Jet.OLEDB.4.0 은 32 bit 에서만 동작되므로 빌드할 때 64비트로 하면 에러가 발생함.
                    connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0;", fileName);
                }
                else if (Path.GetExtension(fileName).ToLower() == ".xlsx")
                {
                    connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties=Excel 12.0;", fileName);
                }
            }

            DataSet data = new DataSet();

            foreach (var sheetName in GetExcelSheetNames(connectionString))
            {
                //MessageBox.Show(sheetName);  // 시트명 출력
                if (sheetName == "Sheet1$")
                {
                    using (OleDbConnection oleConn = new OleDbConnection(connectionString))
                    {
                        var    dataTable = new DataTable();
                        string strQuery  = string.Format("SELECT * FROM [{0}]", sheetName);
                        oleConn.Open();
                        OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, oleConn);
                        adapter.Fill(dataTable);
                        data.Tables.Add(dataTable);
                    }
                }
            }

            dgv.DataSource = data.Tables[0].DefaultView;

            // 데이터에 맞게 칼럼 사이즈 조정하기
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
            }
            dgv.AllowUserToAddRows = false;  // 빈레코드 표시 안하기
            dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
            //dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }
Example #19
0
 public static void adjustColumnsWidth(DataGridView sheet)
 {
     for (int colidx = 0; colidx < sheet.ColumnCount; colidx++)
     {
         if (sheet.RowCount == 0)
         {
             sheet.Columns[colidx].Width = 200;
         }
         else
         {
             sheet.Columns[colidx].Width = 10000;                     // 一旦思いっきり広げてからでないとダメな時がある。
             sheet.AutoResizeColumn(colidx, DataGridViewAutoSizeColumnMode.AllCells);
         }
     }
 }
Example #20
0
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;

            //int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始
            foreach (Control c in ctl.Controls)
            { //**放在这里,是先缩放控件的子控件,后缩放控件本身
                //if (c.Controls.Count > 0)
                //   AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                ctrLeft0   = oldCtrl[ctrlNo].Left;
                ctrTop0    = oldCtrl[ctrlNo].Top;
                ctrWidth0  = oldCtrl[ctrlNo].Width;
                ctrHeight0 = oldCtrl[ctrlNo].Height;
                //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例
                //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;
                c.Left   = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                c.Top    = (int)((ctrTop0) * hScale);  //
                c.Width  = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                c.Height = (int)(ctrHeight0 * hScale); //
                ctrlNo++;
                if (c.Controls.Count > 0)
                {
                    AutoScaleControl(c, wScale, hScale);
                }
                if (ctl is DataGridView)
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;
                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                        widths += dgv.Columns[i].Width;
                    }
                    if (widths >= ctl.Size.Width)
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
                    }
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    }

                    Cursor.Current = Cursors.Default;
                }
            }
        }
        /// <summary>
        /// 自动缩放控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="wScale"></param>
        /// <param name="hScale"></param>
        private void AutoScaleControl(Control ctl, float wScale, float hScale)
        {
            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;

            //int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始
            foreach (Control c in ctl.Controls)
            {
                var olf_control = oldControl.Find(row => row.Name == c.Name);
                if (olf_control == null)
                {
                    continue;
                }
                ctrLeft0   = olf_control.Left;
                ctrTop0    = olf_control.Top;
                ctrWidth0  = olf_control.Width;
                ctrHeight0 = olf_control.Height;
                c.Left     = (int)((ctrLeft0) * wScale); //新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
                c.Top      = (int)((ctrTop0) * hScale);  //
                c.Width    = (int)(ctrWidth0 * wScale);  //只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
                c.Height   = (int)(ctrHeight0 * hScale); //
                if (c.Controls.Count > 0)
                {
                    AutoScaleControl(c, wScale, hScale);//窗体内其余控件还可能嵌套控件(比如panel),要单独抽出,因为要递归调用
                }
                if (ctl is DataGridView)
                {
                    DataGridView dgv = ctl as DataGridView;
                    Cursor.Current = Cursors.WaitCursor;

                    int widths = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);         // 自动调整列宽
                        widths += dgv.Columns[i].Width;                                           // 计算调整列后单元列的宽度和
                    }
                    if (widths >= ctl.Size.Width)                                                 // 如果调整列的宽度大于设定列宽
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 调整列的模式 自动
                    }
                    else
                    {
                        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;  // 如果小于 则填充
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
Example #22
0
        private void setDataGridViewWidth(DataGridView dgv)
        {
            int width = 0;

            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                width += dgv.Columns[i].Width;
            }
            if (width > dgv.Size.Width)
            {
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
        }
        void ShowCourses(String Query, DataGridView DGV)
        {
            SqlConnection  con = new SqlConnection(@"Data Source=AD-PC\SQLEXPRESS10;Initial Catalog = tlogin; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False");
            SqlDataAdapter sda = new SqlDataAdapter(Query, con);
            DataTable      dt  = new DataTable();

            sda.Fill(dt);
            DGV.DataSource = dt;
            DGV.ReadOnly   = true;
            DGV.AutoResizeColumn(0);
            DGV.AutoResizeColumn(1);
            DGV.AutoResizeColumn(2);
            DGV.AutoResizeColumn(3);
            DGV.AutoResizeColumn(4);
            DGV.AutoResizeColumn(5);
            DGV.AutoResizeColumn(6);
        }
        public void HandleDataGridView(DataGridView item)
        {
            for (int j = 0; j < 2; j++)
            {
                dataGridView1.Columns[0].Frozen = false;//固定列

                var width = 0;
                for (int i = 0; i < item.Columns.Count; i++)
                {
                    //将每一列都调整为自动适应模式
                    item.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                    //记录整个DataGridView的宽度
                    width += item.Columns[i].Width;
                }
                item.AutoSizeColumnsMode = width > item.Size.Width ? DataGridViewAutoSizeColumnsMode.DisplayedCells : DataGridViewAutoSizeColumnsMode.Fill;

                dataGridView1.Columns[0].Frozen = true;//固定列
            }
        }
Example #25
0
        public void ShowMakeUpClass(String Query, DataGridView DGV)

        {
            SqlConnection  Sq  = new SqlConnection(Global.ConString);
            SqlDataAdapter sda = new SqlDataAdapter(Query, Sq);
            DataTable      dt  = new DataTable();

            sda.Fill(dt);
            DGV.DataSource = dt;
            DGV.ReadOnly   = true;
            DGV.AutoResizeColumn(0);
            DGV.AutoResizeColumn(1);
            DGV.AutoResizeColumn(2);
            DGV.AutoResizeColumn(3);
            DGV.AutoResizeColumn(4);
            DGV.AutoResizeColumn(5);
            DGV.AutoResizeColumn(6);
        }
 public static void AjustaGrid(DataGridView dtg)
 {
     try
     {
         for (int i = 0; i < dtg.Columns.Count; i++)
         {
             if (dtg.Columns[i].Name.ToString().ToLower() == "id_invisible")
             {
                 dtg.Columns[i].Visible = false;
             }
             else
             {
                 dtg.AutoResizeColumn(i);
             }
             if (dtg.Columns[i].ValueType == typeof(System.Decimal))
             {
                 dtg.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                 //dtg.Columns[i].DefaultCellStyle.Format = "###,##0.##" //n2;
             }
             if (dtg.Columns[i].ValueType == typeof(System.Double))
             {
                 dtg.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
             }
             if (dtg.Columns[i].ValueType == typeof(System.Int16))
             {
                 dtg.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
             }
             if (dtg.Columns[i].ValueType == typeof(System.Int32))
             {
                 dtg.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
             }
             if (dtg.Columns[i].ValueType == typeof(System.Int64))
             {
                 dtg.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #27
0
 public void LoadDataGrid(DataGridView MyDataGridView, string sqlQueryString)
 {
     try
     {
         MyDataGridView.DataSource = null;
         OleDbDataAdapter dA = new OleDbDataAdapter(sqlQueryString, connectionString);
         DataSet          ds = new DataSet();
         dA.Fill(ds);
         MyDataGridView.DataSource = ds.Tables[0].DefaultView;
         MyDataGridView.ReadOnly   = true;
         for (int i = 0; i < MyDataGridView.Columns.Count; i++)
         {
             MyDataGridView.AutoResizeColumn(i);
         }
     }
     catch (SystemException ex)
     {
         MessageBox.Show(ex.StackTrace.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Example #28
0
        public static void ajustarTamañoTabla(DataGridView tabla)
        {
            for (int i = 0; i < tabla.RowCount; i++)
            {
                DataGridViewRow d = tabla.Rows[i];
                for (int j = 0; j < d.Cells.Count; j++)
                {
                    string x = d.Cells[j].Value.ToString();
                    d.Cells[j].Value = d.Cells[j].Value.ToString().Trim();
                }

                /*string x = d.Cells[1].Value.ToString();
                 * d.Cells[1].Value = d.Cells[1].Value.ToString().Trim();*/
            }
            for (int j = 0; j < tabla.ColumnCount; j++)
            {
                tabla.AutoResizeColumn(j);
            }
            //tabla.Rows.RemoveAt(tabla.Rows.Count-1);
        }
Example #29
0
        private void AddDataViewToCurrentTab()
        {
            var list = entities.major.Select(x => new { x.id, Ad = x.name }).ToList();

            switch ((Types)tabControl1.SelectedIndex)
            {
            case Types.Family:
                int id = Selections[Types.Major].Id;
                list = entities.family.Where(x => x.majorid == id).Select(x => new { x.id, Ad = x.name }).ToList();
                break;

            case Types.Genus:
                id   = Selections[Types.Family].Id;
                list = entities.genus.Where(x => x.familyid == id).Select(x => new { x.id, Ad = x.name }).ToList();
                break;

            case Types.Species:
                id   = Selections[Types.Genus].Id;
                list = entities.species.Where(x => x.genusid == id).Select(x => new { x.id, Ad = x.name }).ToList();
                break;

            case Types.Synonym:
                id   = Selections[Types.Species].Id;
                list = entities.synonym.Where(x => x.speciesid == id).Select(x => new { x.id, Ad = x.name }).ToList();
                break;

            default:
                break;
            }
            BindingSource bs = new BindingSource();
            var           dt = new Class.DataProcess().GetDataTableFromList(list);

            bs.DataSource = dt;
            bindingNavigator1.BindingSource = bs;
            GridView.DataSource             = dt;

            GridView.Columns["id"].Visible = false;
            GridView.AutoResizeColumn(1);
            tabControl1.SelectedTab.Controls.Clear();
            tabControl1.SelectedTab.Controls.Add(pnlContainer);
        }
Example #30
0
        public void SetAutoResizeCells(ref DataGridView dataGrid)
        {
            if ((dataGrid == null) || (dataGrid.Columns.Count < 1))
            {
                return;
            }

            dataGrid.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            dataGrid.AutoSizeRowsMode          = DataGridViewAutoSizeRowsMode.AllCells;

            DataGridViewColumnCollection columns = dataGrid.Columns;

            for (int index = 0; index < columns.Count; index++)
            {
                DataGridViewColumn column = columns[index];

                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

                dataGrid.AutoResizeColumn(index);
            }
        }