欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.Net使用XtraGrid控件綁定數(shù)據(jù)

 更新時間:2022年06月02日 09:51:38   作者:springsnow  
這篇文章介紹了.Net使用XtraGrid控件綁定數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

設(shè)計數(shù)據(jù)源并綁定字段:

數(shù)據(jù)源可以是實現(xiàn)下列接口之一的任何類型:

修改也是同步的

DataTable dataTable = new DataTable();
dataTable.Columns.Add("Name", System.Type.GetType("System.String"));
dataTable.Columns.Add("Sex", System.Type.GetType("System.String"));
dataTable.Columns.Add("Age", System.Type.GetType("System.String"));

DataRow row = dt.NewRow(); ;
row["Name"] = "mathilda";
row["Sex"] = "loli";
row["Age"] = "12";
dataTable.Rows.Add(row);

// 綁定字段
gridView1.Columns[1].FieldName = "Sex";
gridView1.Columns[2].FieldName = "Age";
gridView1.Columns[0].FieldName = "Name";

gridControl1.DataSource = dataTable;

根據(jù)數(shù)據(jù)源自動產(chǎn)生列

gridView2.PopulateColumns();

表格數(shù)據(jù)與數(shù)據(jù)源的數(shù)據(jù)同步

XtraGrid與Windows自帶的DataGridView在數(shù)據(jù)源方面不同的是,對grid里的數(shù)據(jù)進(jìn)行任何改動(增、刪、改)之后,原本的數(shù)據(jù)源也相應(yīng)的改動。通過下面例子可以得出此結(jié)論,在窗體添加刪,改兩個按鈕并綁定下面相應(yīng)的事件。

/// <summary>
/// 更改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btEdit_Click(object sender, EventArgs e)
{
    Person p = (Person)gridView1.GetRow(gridView1.FocusedRowHandle);
}

/// <summary>
/// 刪除
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btDelete_Click(object sender, EventArgs e)
{
    if (gridView1.SelectedRowsCount != 0)
        gridView1.DeleteSelectedRows();
    MessageBox.Show(people.Count.ToString());
}

只要對grid的數(shù)據(jù)經(jīng)過改動之后,單擊相應(yīng)的按鈕就可以查看數(shù)據(jù)源的信息。

新增一條記錄,添加行

(1)、gridView.AddNewRow()、gridView.UpdateCurrentRow()

數(shù)據(jù)源DataSource如果是DataTable可以用AddNewRow方法,然后UpdateCurrentRow。

但是如果DataSource的來源是List<T>,用AddNewRow是不起作用的,這時候需要將List<T>轉(zhuǎn)換為BindingList<T>,才可以采用AddNewRow。

然后使用gridView.UpdateCurrentRow()將更改同步到數(shù)據(jù)源DataTable或BindingList中。

(2)、實現(xiàn) gridView_InitNewRow 事件

刪除選中行

刪除選中行, 可通過DeleteSelectedRows()方法,

然后使用gridView.UpdateCurrentRow()將更改同步到數(shù)據(jù)源DataTable或BindingList中。

具體示例代碼如下:

if (gridView1.SelectedRowsCount > 0)
{
     gridView1.DeleteSelectedRows();
     gridView.UpdateCurrentRow()
}

獲取選定行,指定列單元格的內(nèi)容

gridView1.GetRowCellValue(pRows[0], ColumName).ToString ();

選擇某行后獲取當(dāng)前表格數(shù)據(jù):

this.textBox1.Text = gridView2.GetDataRow(e.RowHandle)["列名"].ToString();

Get/Set 單元格的值

通過調(diào)用GetRowCellValue獲取單元格的值。

public override object GetRowCellValue(int rowHandle, GridColumn column);

rowHandle是行的索引,column列的對象。

通過調(diào)用SetRowCellValue設(shè)置單元格的值

public void SetRowCellValue(int rowHandle, GridColumn column, object _value);

rowHandle是行的索引,column列的對象。_value是單元格新的值。

以peopleList為例

int englishS=Convert.ToDouble(0,gridView1.Columns["English"])+60;
SetRowCellValue(0,gridView1.Columns["English"],englishS);

在XtraGrid有另一種方式,就是直接設(shè)置數(shù)據(jù)源的值。對于上面這個例子,直接找到grid里第一行數(shù)據(jù)對應(yīng)的Person對象,設(shè)置它的English值。

選中行改變綁定行數(shù)據(jù)到對應(yīng)控件中

1、判斷是否有Focused行

if (gridView1.IsValidRowHandle(gridView1.FocusedRowHandle))

2、獲取Focused行

1、綁定的是數(shù)據(jù)行:

DataRow Row = gridView1.GetFocusedDataRow();

2、綁定的是實體:

**Entity entity = gridView1.GetFocusedRow() as **Entity;

3、獲取Focused行單元格的值

string Code = gridView1.GetFocusedRowCellValue("Code").ToString();
string Code = gridView1.GetRowCellValue(e.FocusedRowHandle, "Code")

FocusedRowChanged事件:

if (bandedGridView1.GetFocusedDataRow() == null) return;//判斷當(dāng)前選中行是否為null
//返回值
var columnValue= bandedGridView1.GetFocusedRowCellValue("綁定列字段名稱").ToString();

動態(tài)添加列

// 動態(tài)添加列             
DevExpress.XtraGrid.Columns.GridColumn Col1 = new DevExpress.XtraGrid.Columns.GridColumn();             
Col1.FieldName = "Name";             
Col1.Caption = "名字";             
Col1.Visible = false;             
Col1.VisibleIndex = gvCountry.Columns.Count;             
gvCountry.Columns.Add(Col1);

添加非綁定列

下面的例子主要演示如何為gird網(wǎng)格添加一個非綁定列,從而顯示根據(jù) Quantity*UnitPrice*(1-Discount)公式計算出來的每個訂單的金額。

private void Form1_Load(object sender, System.EventArgs e)
{
    // ...
    gridControl1.ForceInitialize();
    // Create an unbound column.
    GridColumn unbColumn = gridView1.Columns.AddField("Total");
    unbColumn.VisibleIndex = gridView1.Columns.Count;
    unbColumn.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
    // Disable editing.
    unbColumn.OptionsColumn.AllowEdit = false;
    // Specify format settings.
    unbColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
    unbColumn.DisplayFormat.FormatString = "c";
    // Customize the appearance settings.
    unbColumn.AppearanceCell.BackColor = Color.LemonChiffon;
}
// Returns the total amount for a specific row.
decimal getTotalValue(int listSourceRowIndex)
{
    DataRow row = nwindDataSet.Tables["Order Details"].Rows[listSourceRowIndex];
    decimal unitPrice = Convert.ToDecimal(row["UnitPrice"]);
    decimal quantity = Convert.ToDecimal(row["Quantity"]);
    decimal discount = Convert.ToDecimal(row["Discount"]);
    return unitPrice * quantity * (1 - discount);
}
// Provides data for the Total column.
private void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
{
    if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
    getTotalValue(e.ListSourceRowIndex);
}

編輯器

XtraGrid提供了多種編輯器。這些能夠在Grid/CardView/BandedView中使用。在屬性編輯器中的In-place Editor Repository可以對編輯器進(jìn)行管理。在Columns的ColumnEdit中選擇該列使用哪個編輯器。

也可以通過代碼實現(xiàn):

RepositoryItemComboBox repositoryItemComboBox_abc=new RepositoryItemComboBox();
// 
// 對編輯器進(jìn)行設(shè)置
// 
this.gridColumn1.ColumnEdit = repositoryItemComboBox_abc;  //在需要的列里使用定義好的編輯器

添加按鈕列

把列的ColumnEdit屬性設(shè)置為RepositoryItemButtonEdit
把TextEditStyle屬性設(shè)置為HideTextEditor;
把Buttons的Kind屬性設(shè)置為Glyph;

把Button的Caption用于設(shè)置文字
把Buttons的TextOption的HAlignment屬性設(shè)置為Near;
如果要用到事件的話,還要注冊事件。。。
在GridControl的設(shè)計器中Repository頁中的In-place Editor Repository項中
在右邊的Repository欄中找到你的ButtonEdit,選它的事件屬性頁,注冊它的ButtonClick事件即可

數(shù)據(jù)驗證

有兩種方法來實現(xiàn)基于單元格的驗證:

1、使用RepositoryItem.Validating事件

事件的"sender" 必須轉(zhuǎn)換為BaseEdit類型,使用EditValue來獲取當(dāng)前輸入的值并進(jìn)行校驗,如果校驗不通過,把e.Cancel設(shè)置True。這種方法一般用來對內(nèi)置控件的單元格進(jìn)行數(shù)據(jù)驗證。

private void TextEdit1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    BaseEdit textEdit = sender as BaseEdit;
    if (textEdit.Text.ToString().Trim().Length == 0)
    {
        e.Cancel = true;
        //標(biāo)識 錯誤提示
        errorReason = 0;
        return;
    }
    else
    {
        //獲取GridView中所有的選中的行號
        //此處不允許多選,故只有一行
        int[] iRowId = this.gViewActList.GetSelectedRows();
        for (int i = 0; i < gViewActList.DataRowCount; i++)
        {
            //重復(fù)檢驗時,不驗證當(dāng)前行
            if (i != iRowId[0])
            {
                if (textEdit.EditValue.ToString().Trim() == gViewActList.GetDataRow(i)["GridView上綁定的列名"].ToString().Trim())
                {
                    e.Cancel = true;
                    //標(biāo)識 錯誤提示
                    errorReason = 1;
                    return;
                }
            }
        }
    }
}

跟據(jù)Validating事件中的標(biāo)識,進(jìn)行錯誤信息提示:

private void gViewActList_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
{
    if (errorReason == 0)
    {
        e.ErrorText = "動作名稱不允許為空!";
    }
    else if (errorReason == 1)
     {
         e.ErrorText = "動作名稱不允許為重復(fù)!";
     }
     else
     {
         e.ErrorText = "值無效!";
     }
}

2、使用 GridView.ValidatingEditor 事件

事件的"sender"必須轉(zhuǎn)換為GridView類型,當(dāng)前列可以從GridView.FocusedColumn屬性獲得,值可以從e.Value獲取,如果校驗不通過,需要把e.Valid設(shè)置為False。這種方法一般用于對整個Grid內(nèi)的文本框進(jìn)行數(shù)據(jù)驗證

private void gvList_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e){
             if (this.gvList.FocusedColumn.FieldName == "passQty"){ 
                string passQty = e.Value.ToString().Trim();                 
                int receiveQty = orderDetailList[this.gvList.FocusedRowHandle].qty; 
                if (!JXType.IsIntBigThanZero(passQty)){ 
                    e.Valid = false;                     
                    e.ErrorText = "合格數(shù)量必須為大于等于0, 并且小于等于接貨數(shù)量的整數(shù)!";
                }else{ 
                    if (int.Parse(passQty) > receiveQty){ 
                        e.Valid = false;                         
                        e.ErrorText = "合格數(shù)量必須為大于0, 并且小于等于接貨數(shù)量的整數(shù)!";
                    }
                }
            }
}

在設(shè)置完事件之后需要寫一個GridView.InvalidValueException 的事件委托,如

private void gridView1_InvalidValueException(object sender, DevExpress.XtraGrid.Views.Base.InvalidValueExceptionEventArgs e)
{
    e.ThrowException = false;
    e.WindowText = "驗證通過";
    e.DisplayError = true;
}

3、使用 GridView.ValidateRow事件

在gridview的ValidateRow事件中加入數(shù)據(jù)校驗代碼:

#region 檢查數(shù)據(jù)   
private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e){
    GridView view = sender as GridView;   
    view.ClearColumnErrors();
    if (view.GetRowCellValue(e.RowHandle, "Birthday") == DBNull.Value){ 
        e.Valid = false;   
        view.SetColumnError(view.Columns["Birthday"], "必須指定出生日期");   
    }
}

添加CheckBox并支持多選操作.

OptionsSelection -> MultiSelect : True

MultiSelectMode : CheckBoxRowSelect

全選和反選

這是一個比較難的問題,這里我結(jié)合網(wǎng)上尋找的資料總結(jié)了一個實體類貼上源代碼

//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2014 , ZTO , Ltd .
 //-------------------------------------------------------------------------------------

using System.Drawing;
 using System.Windows.Forms;
 using DevExpress.XtraEditors.Repository;

namespace ZTO.WayBill.Utilities
 {
     /// <summary>
     /// Dev GridControl 創(chuàng)建全選復(fù)選框
    ///
     /// 修改紀(jì)錄
    ///
     ///          2014-5-30   版本:1.0 YangHengLian 創(chuàng)建主鍵,注意命名空間的排序。
    /// 
     /// 版本:1.0
     ///
     /// <author>
     ///        <name>YangHengLian</name>
    ///        <date>2014-5-30</date>
     /// </author>
     /// </summary>
     public class DevControlHelper
     {
         /// <summary>
         /// 創(chuàng)建復(fù)選框
        /// </summary>
         /// <param name="e"></param>
         /// <param name="chk"></param>
         public static void DrawCheckBox(DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e, bool chk)
         {
             RepositoryItemCheckEdit repositoryCheck = e.Column.ColumnEdit as RepositoryItemCheckEdit;
             if (repositoryCheck != null)
             {
                 Graphics g = e.Graphics;
                 Rectangle r = e.Bounds;
                 DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
                 DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
                 DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
                 info = repositoryCheck.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
                 painter = repositoryCheck.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
                 info.EditValue = chk;
                 info.Bounds = r;
                 info.CalcViewInfo(g);
                 args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
                 painter.Draw(args);
                 args.Cache.Dispose();
             }
         }
         /// <summary>
         /// 全選,反選
        /// </summary>
         /// <param name="gridView"></param>
         /// <param name="fieldName"></param>
         /// <param name="currentStatus"></param>
         /// <returns></returns>
         public static bool ClickGridCheckBox(DevExpress.XtraGrid.Views.Grid.GridView gridView, string fieldName, bool currentStatus)
         {
             bool result = false;
             if (gridView != null)
             {
                 gridView.ClearSorting();//禁止排序
                gridView.PostEditor();
                 DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info;
                 Point pt = gridView.GridControl.PointToClient(Control.MousePosition);
                 info = gridView.CalcHitInfo(pt);
                 if (info.InColumn && info.Column != null && info.Column.FieldName == fieldName)
                 {
                     for (int i = 0; i < gridView.RowCount; i++)
                     {
                         gridView.SetRowCellValue(i, fieldName, !currentStatus);
                     }
                     return true;
                 }
             }
             return result;
         }
     }
 }

下面是使用步驟

窗體加載事件添加一些代碼

private bool _mCheckStatus; //GridControl全選,作為全局變量,默認(rèn)false
        private void FrmInputBill_Load(object sender, EventArgs e)
        {
            bandedGridView1.OptionsBehavior.Editable = false;
            bandedGridView1.OptionsBehavior.ReadOnly = true;
            var col = new BandedGridColumn { FieldName = "Check", Visible = true, VisibleIndex = 0, ColumnEdit = new RepositoryItemCheckEdit() };
            col.OptionsColumn.AllowEdit = true; //CheckBox可以編輯改變
            gridBand1.Columns.Insert(0, col);
            bandedGridView1.Click += bandedGridView1_Click;
            bandedGridView1.CustomDrawColumnHeader += bandedGridView1_CustomDrawColumnHeader;
            bandedGridView1.DataSourceChanged += bandedGridView1_DataSourceChanged;
       //這里綁定數(shù)據(jù)源
        }
        #region GridControl支持全選事件
 
        private void bandedGridView1_Click(object sender, EventArgs e)
        {
            if (DevControlHelper.ClickGridCheckBox(this.bandedGridView1, "Check", _mCheckStatus))
            {
                _mCheckStatus = !_mCheckStatus;
            }
        }
 
        private void bandedGridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "Check")
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DevControlHelper.DrawCheckBox(e, _mCheckStatus);
                e.Handled = true;
            }
        }
 
        private void bandedGridView1_DataSourceChanged(object sender, EventArgs e)
        {
            GridColumn column = this.bandedGridView1.Columns.ColumnByFieldName("Check");
            if (column != null)
            {
                column.Width = 40;
                column.OptionsColumn.ShowCaption = false;
                column.ColumnEdit = new RepositoryItemCheckEdit();
            }
        }
 
        #endregion

重繪單元格或者行的顯示,使用CustomDrawCell()事件

通過在Appearence中添加FormatCondition,設(shè)置應(yīng)用與整行,還是單一個單元格,使用CustomDrawCell事件。

void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
    var currentView = sender as GridView;
    if (currentView != null && e.RowHandle == currentView.FocusedRowHandle) return;
    Rectangle r = e.Bounds;
    if (e.Column.FieldName == "F_State")
    {
        if (e.CellValue.ToString().Equals("False"))
        {
            e.Appearance.ForeColor = Color.Red;
            e.Appearance.DrawString(e.Cache, e.DisplayText, r);
            e.Handled = true;
        }

    }
}

數(shù)據(jù)導(dǎo)入導(dǎo)出

原文:Export to XLS and XLSX Formats | WinForms Controls | DevExpress Documentation

XtraGrid 支持Html、Xml、Txt、Xsl導(dǎo)出,對應(yīng)的導(dǎo)出器是ExportHtmlProvider、ExportXmlProvider、 ExportTxtProvider、ExportXslProvider。都在命名空間DevExpress.XtraExport里面。

這里封裝了一個數(shù)據(jù)導(dǎo)出的方法,可以導(dǎo)出上述列舉的類型,只需要傳入相應(yīng)類型的provider就可以了。

private void ExportTo(IExportProvider provider)
{
    Cursor currentCursor = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    this.FindForm().Refresh();
    BaseExportLink link = gridView1.CreateExportLink(provider);
    (link as GridViewExportLink).ExpandAll = false;
    link.ExportTo(true);
    provider.Dispose();
    Cursor.Current = currentCursor;
}

調(diào)用時只需要創(chuàng)建一個相應(yīng)的provider。

IExportProvider provider = new ExportXlsProvider(FullFileName); //這里可以是ExportHtmlProvider、ExportXmlProvider、ExportTxtProvider
ExportTo(provider);

也可以

string path = "output.xlsx";

//Customize export options
(gridControl1.MainView as GridView).OptionsPrint.PrintHeader = false;
XlsxExportOptionsEx advOptions = new XlsxExportOptionsEx();
advOptions.AllowGrouping = DevExpress.Utils.DefaultBoolean.False;
advOptions.ShowTotalSummaries = DevExpress.Utils.DefaultBoolean.False;
advOptions.SheetName = "Exported from Data Grid";

gridControl1.ExportToXlsx(path, advOptions);
// Open the created XLSX file with the default application.
Process.Start(path);

導(dǎo)入數(shù)據(jù)只嘗試了導(dǎo)入Excel的導(dǎo)入,利用ODBC讀取Excel的數(shù)據(jù)到DataTable中,再把DataTable綁定到XtraGrid中。這里也是封裝了一個讀取Excel數(shù)據(jù)的方法。

private DataSet GetDataFromExcelWithAppointSheetName(string Path)
{
    String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + Path + ";" +"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();
    //返回Excel的架構(gòu),包括各個sheet表的名稱,類型,創(chuàng)建時間和修改時間等 
    DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
    //包含excel中表名的字符串?dāng)?shù)組
    string[] strTableNames = new string[dtSheetName.Rows.Count];
    for (int k = 0; k < dtSheetName.Rows.Count; k++)
    {
        strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
    }
    OleDbDataAdapter da = null;
    DataSet ds = new DataSet();
    //從指定的表明查詢數(shù)據(jù),可先把所有表明列出來供用戶選擇
    string strExcel = "select * from[" + strTableNames[0] + "]";
    da = new OleDbDataAdapter(strExcel, conn);
    da.Fill(ds);
    return ds;
}

以這樣方式調(diào)用。

DataSet ds = GetDataFromExcelWithAppointSheetName(FullFileName);

導(dǎo)出到PDF

一種方法:

using DevExpress.XtraPrinting;

// Create a PrintingSystem component.
DevExpress.XtraPrinting.PrintingSystem ps = new DevExpress.XtraPrinting.PrintingSystem();

// Create a link that will print a control.
DevExpress.XtraPrinting.PrintableComponentLink link = new PrintableComponentLink(ps);

// Specify the control to be printed.
link.Component = gridControl1;

// Generate a report.
link.CreateDocument();

// Export the report to a PDF file.
string filePath = @"c:\gridcontrol.pdf";
link.PrintingSystem.ExportToPdf(filePath);

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = filePath;
process.Start();

二種:

DevExpress.XtraGrid.Views.Grid.GridView View = gridControl1.MainView    as DevExpress.XtraGrid.Views.Grid.GridView;
if (View != null) {
   View.OptionsPrint.ExpandAllDetails = true;//請注意,僅當(dāng)GridOptionsPrint.PrintDetails屬性設(shè)置為true時,此設(shè)置才有效。
   View.ExportToPdf("MainViewData.pdf");
}

行雙擊事件的處理

要響應(yīng)GridView的單擊或者雙擊事件,要設(shè)置GridView的OptionsBehavior.Editable=false。如果為true,它是不會響應(yīng)這這兩個事件的。 它本的的機制就是這樣。

//雙擊行彈出rowDetail信息 
        private void gridView1_MouseDown(object sender, MouseEventArgs e) 
        {  
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X,e.Y));  
            if (gridView1.RowCount > 0 && e.Button == MouseButtons.Left && e.Clicks == 2) 
            {  
                //判斷光標(biāo)是否在行范圍內(nèi)  
                if (hInfo.InRow)  
                {  
                    //取得選定行信息  
                    string nodeName = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "nodeName").ToString(); 
                    //string nodeName = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "nodeName").ToString(); 
                    string sql = "select nodeDetail from treelist where nodeName = '" + nodeName + "'"; 
                    SqlCommand comm = new SqlCommand(sql, conn);  
                    try 
                    {  
                        conn.Open();  
                        MessageBox.Show(comm.ExecuteScalar().ToString(), "Detail"); 
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.Message, "Error"); 
                    }  
                    finally 
                    {  
                        conn.Close();  
                    }  
                }  
            }  
        }

那么MouseDown方法與DoubleClick有什么區(qū)別呢?grid1_DoubleClick(object sender, EventArgs e)函數(shù)會捕獲整個grid的雙擊事件而不僅僅是雙擊列表行事件,比如:你雙擊表頭、列表展示數(shù)據(jù)的下方的空白部分都會引發(fā)grid1_DoubleClick(object sender, EventArgs e)函數(shù),而ViewHtlb_MouseDown(object sender, MouseEventArgs e)函數(shù)此時不會被激活。

定位到某數(shù)據(jù)/記錄??

this.gridView.MoveFirst();
this.gridView.MoveNext();
this.gridView.MoveLast();

禁止 各列頭 移動\排序\改變列寬

gridView1.OptionsCustomization.AllowColumnMoving = false;
gridView1.OptionsCustomization.AllowSort = false;
gridView1.OptionsCustomization.AllowColumnResizing = false;

拖動滾動條時固定某一列

設(shè)置Columns,選擇要固定的列,設(shè)置Fixed屬性,

可以選擇以下固定方式:

  • a. 固定在左邊、
  • b. 固定在右邊、
  • c. 不固定。

呈現(xiàn)給用戶自定義的菜單:

#region Grid events
        private void gridView_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Column)
            {
                DevExpress.XtraGrid.Menu.GridViewColumnMenu menu = e.Menu as DevExpress.XtraGrid.Menu.GridViewColumnMenu;
                menu.Items.Clear();
                if (menu.Column != null)
                {
                    menu.Items.Add(CreateCheckItem("取消固定", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.None, imageList2.Images[0]));
                    menu.Items.Add(CreateCheckItem("固定到左邊", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.Left, imageList2.Images[1]));
                    menu.Items.Add(CreateCheckItem("固定到右邊", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.Right, imageList2.Images[2]));
                }
            }
        }

        #endregion
        #region New column menu
        DXMenuCheckItem CreateCheckItem(string caption, GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style, Image image)
        {
            DXMenuCheckItem item = new DXMenuCheckItem(caption, column.Fixed == style, image, new EventHandler(OnFixedClick));
            item.Tag = new MenuInfo(column, style);
            return item;
        }
        void OnFixedClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            MenuInfo info = item.Tag as MenuInfo;
            if (info == null) return;
            info.Column.Fixed = info.Style;
        }
        class MenuInfo
        {
            public MenuInfo(GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style)
            {
                this.Column = column;
                this.Style = style;
            }
            public DevExpress.XtraGrid.Columns.FixedStyle Style;
            public GridColumn Column;
        }
        #endregion

設(shè)置自動增加的行號

this.gridView1.IndicatorWidth = 30;//設(shè)置顯示行號的列寬

private void gridview_CustomDrawRowIndicator(object sender,DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e){

     e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
     if(e.Info.IsRowIndicator){
        if(e.RowHandle >= 0){
            e.Info.DisplayText = (e.RowHandle + 1).ToString();                 
        }else if(e.RowHandle > -1000 && e.RowHandle < 0){
            e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
            e.Info.DisplayText = "G" + e.RowHandle.ToString();                 
        }             
     }
}

在查詢得到 0 條記錄時, 顯示自定義的字符提示

// When no Records Are Being Displayed
private void gridView1_CustomDrawEmptyForeground(object sender, CustomDrawEventArgs e)
{
    // 方法一(此方法為GridView設(shè)置了數(shù)據(jù)源綁定時,可用)
    ColumnView columnView = sender as ColumnView;
    BindingSource bindingSource = this.gridView1.DataSource as BindingSource;
    if(bindingSource.Count == 0){
        string str = "沒有查詢到你所想要的數(shù)據(jù)!";
        Font f = new Font("宋體", 10, FontStyle.Bold);        
        var tmpLeft = e.Bounds.Left + 5;
        var tmpTop = e.Bounds.Top + 5;
        var tmpWidth = e.Bounds.Width - 5;
        var tmpHeight = e.Bounds.Height - 5;
        Rectangle r = new Rectangle(tmpLeft, tmpTop, tmpWidth, tmpHeight);
        e.Graphics.DrawString(str, f, Brushes.Black, rect); 
    }
}
// 方法二(此方法 適用于: GridView 沒有設(shè)置數(shù)據(jù)源時)
if (this._flag){
 if (this.gridView1.RowCount == 0){ 
    string str = "沒有查詢到你所想要的數(shù)據(jù)!"; 
    Font f = new Font("宋體", 10, FontStyle.Bold);
    var tmpLeft = e.Bounds.Left + 5;
    var tmpTop = e.Bounds.Top + 5;
    var tmpWidth = e.Bounds.Width - 5;
    var tmpHeight = e.Bounds.Height - 5;
    Rectangle r = new Rectangle(tmpLeft, tmpTop, tmpWidth, tmpHeight);
    e.Graphics.DrawString(str, f, Brushes.Black, r); 
 } 
}

到此這篇關(guān)于.Net使用XtraGrid控件綁定數(shù)據(jù)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解ABP框架中Session功能的使用方法

    詳解ABP框架中Session功能的使用方法

    ABP(ASP.NET Boilerplate Project)是基于ASP.NET框架的一個Web開發(fā)框架,這里我們來詳解ABP框架中Session功能的使用方法,需要的朋友可以參考下
    2016-06-06
  • ASP.NET?Core中的通用主機HostBuilder

    ASP.NET?Core中的通用主機HostBuilder

    這篇文章介紹了ASP.NET?Core中的通用主機HostBuilder,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • 讀取TXT文件內(nèi)容的方法

    讀取TXT文件內(nèi)容的方法

    讀取TXT文件內(nèi)容的方法...
    2006-10-10
  • Blazor路由與頁面導(dǎo)航開發(fā)介紹

    Blazor路由與頁面導(dǎo)航開發(fā)介紹

    這篇文章介紹了Blazor路由與頁面導(dǎo)航開發(fā),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-01-01
  • .Net創(chuàng)建型設(shè)計模式之抽象工廠模式(Abstract?Factory)

    .Net創(chuàng)建型設(shè)計模式之抽象工廠模式(Abstract?Factory)

    這篇文章介紹了.Net設(shè)計模式之抽象工廠模式(Abstract?Factory),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • .NET2.0版本中基于事件的異步編程模式(EAP)

    .NET2.0版本中基于事件的異步編程模式(EAP)

    這篇文章介紹了.NET2.0版本中基于事件的異步編程模式(EAP),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • .Net結(jié)構(gòu)型設(shè)計模式之享元模式(Flyweight)

    .Net結(jié)構(gòu)型設(shè)計模式之享元模式(Flyweight)

    這篇文章介紹了.Net結(jié)構(gòu)型設(shè)計模式之享元模式(Flyweight),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • .net?6精簡版webapi教程及熱重載、代碼自動反編譯演示

    .net?6精簡版webapi教程及熱重載、代碼自動反編譯演示

    這篇文章介紹了.net?6精簡版webapi教程及熱重載、代碼自動反編譯演示,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-12-12
  • WPF中Style樣式及其觸發(fā)器

    WPF中Style樣式及其觸發(fā)器

    這篇文章介紹了WPF中Style樣式及其觸發(fā)器,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-01-01
  • ASP.NET Table 表格控件的使用方法

    ASP.NET Table 表格控件的使用方法

    使用 Table 控件可以在 ASP.NET 網(wǎng)頁上創(chuàng)建服務(wù)器可編程的表格。如果要創(chuàng)建的是靜態(tài)表格(運行時不會在其中添加或更改內(nèi)容的表格),則應(yīng)使用 HTML 表格,而不是 Table 控件。
    2016-04-04

最新評論