熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

DataGrid使用心得(附大量代碼)

2022-06-13   來源: .NET編程 

  為DataGrid控件設計樣式
   
   在<asp:datagridid=DataGridrunat=server>之後添加如下代碼
   
   <FooterStyleForeColor=BlackBackColor=#CCCCCC></FooterStyle>
   <SelectedItemStyleFontBold=TrueForeColor=WhiteBackColor=#AC></SelectedItemStyle>
   <AlternatingItemStyleBackColor=Gainsboro></AlternatingItemStyle>
   <ItemStyleForeColor=BlackBackColor=#EEEEEE></ItemStyle>
   <HeaderStyleFontBold=TrueForeColor=WhiteBackColor=#></HeaderStyle>
   
   說明:
   ()在每個標簽內主要是 ForeColor  BackColor FontBold這幾個屬性值
   
  為DataGrid控件添加綁定列
   
   <asp:BoundColumnDataField=ReadOnly=TrueHeaderText=></asp:BoundColumn>
   說明:
   ()在標簽內的基本屬性是DataField/HeaderText
   ()DataFormatString用於獲取或設置指定列中各項的顯示格式的字符串
    形式為{A:Bxx}例如格式化字符串{:F}將顯示帶兩位小數的定點數
    其中A值只能設置為因為每個單元格中只有一個值
    冒號後的字符(常規示例中為B)指定值的顯示格式
    C 以貨幣格式顯示數值
       D 以十進制格式顯示數值
       E 以科學記數法(指數)格式顯示數值
       F 以固定格式顯示數值
       G 以常規格式顯示數值
       N 以數字格式顯示數值
       X 以十六進制格式顯示數值
   ()Visible獲取或設置一個值該值指示此列在DataGrid控件中是否可見
   ()ReadOnly設置些列是否只讀若是只讀的話則不能修改
   ()SortExpression獲取或設置選擇進行排序的列時傳遞到OnSortCommand方法的字段或表達式的名稱
  

  為DataGrid控件添加模板列

   <asp:TemplateColumnHeaderText=類別>
    <ItemTemplate>
     <asp:LabelText=<%#DataBinderEval(ContainerDataItemactorclassname)%>runat=serverID=Label/>
    </ItemTemplate>
    <EditItemTemplate>
     <selectname=sltclassname>
      <%=ActorClassGetParentClass()%>
     </select>
    </EditItemTemplate>
   </asp:TemplateColumn>

說明:

   ()基本框架是

    <asp:TemplateColumnHeaderText=類別>
    <ItemTemplate></ItemTemplate>
    </asp:TemplateColumn>

   ()全面的模板列

    <asp:TemplateColumn>

  <HeaderTemplate>
                 <b>Tax</b>
              </HeaderTemplate>

  <ItemTemplate>
                 <asp:Label
                      Text=<%#DataBinderEval(ContainerDataItemTax)%>
                      runat=server/>
              </ItemTemplate>

  <EditItemTemplate>

  <asp:CheckBox
                      Text=Taxable
                      runat=server/>

  </EditItemTemplate>

  <FooterTemplate>
                 <asp:HyperLinkid=HyperLink
                      Text=Microsoft
                      NavigateUrl=
                      runat=server/>
              </FooterTemplate>

  </asp:TemplateColumn>

 ()為布爾型列應用模板列

  <asp:TemplateColumn>
        <ItemTemplate>
            <asp:Label
                Text=<%#DataBinderEval(ContainerDataItemTax)%>
                    runat=server/>
           </ItemTemplate>
           <EditItemTemplate>
            <asp:CheckBox
                Text=Taxable
                    runat=server/>

  </EditItemTemplate>
       </asp:TemplateColumn>
       在正常狀態用Label控件顯示
       在編輯狀態用CheckBox控件顯示
   
 () 為枚舉類型列應用模板列如業務地區(全網/廣東/雲南等等)

  <asp:TemplateColumnHeaderText=處理方式>
   <ItemTemplate>
    <asp:LabelID=lbStatus>
     <%#DataBinderEval(ContainerDataItemDealWith)%>
    </asp:Label>
   </ItemTemplate>
   <EditItemTemplate>
    <asp:DropDownListid=dpStatusrunat=serverDataTextField=status>
     <asp:ListItemValue=Log>Log(日志)</asp:ListItem>
     <asp:ListItemValue=SendSms>SendSms(短信)</asp:ListItem>
    </asp:DropDownList>
   </EditItemTemplate>
  </asp:TemplateColumn>
  在正常狀態用Label控件顯示
  在編輯狀態用DropDownList控件顯示
 
 ()為長字符串應用模板列如一篇文章的內容
   還未做過
  
 為DataGrid控件添加按鈕列
 
 <asp:ButtonColumn
       HeaderText=Removefromcart
       ButtonType=PushButton
       Text=Remove
       CommandName=RemoveFromCart/>
   ()要使用按鈕列必須在DataGrid控件中添加OnItemCommand屬性並為該事件添加處理方法
   ()模板列可以實現按鈕列能實現的任何功能
   
   為DataGrid控件添加編輯列

   <asp:EditCommandColumnButtonType=LinkButtonUpdateText=更新HeaderText=編輯CancelText=取消EditText=編輯></asp:EditCommandColumn>
   ()ButtonType有兩個值:LinkButton超級鏈接樣式按鈕的列|PushButton普通按鈕的列

  為DataGrid控件添加超鏈接列

 <asp:HyperLinkColumnText=添加子類DataNavigateUrlField=ActorclassIDDataNavigateUrlFormatString=addActorClassaspx?classID={}></asp:HyperLinkColumn>

 ()為每一行設置相同的文字及跳轉的URL地址

  設置Text和NavigateUrl屬性則列中的所有超級鏈接將共享同一標題和URL

 ()為每一行設置不同的文字及不同跳轉的URL地址

  A 用DataTextField設置數據源字段若還想在原數據的基礎上加工一下(如字段值為想顯示為元)
   則再設置DataTextFormatString字段
  B 用DataNavigateUrlField及DataNavigateUrlFormatString來設置URL地址
   用DataTextField=moneyDataTextFormatString={}元
  C 舉例
   DataNavigateUrlField=ActorclassIDDataNavigateUrlFormatString=addActorClassaspx?classID={}
   
 為DataGrid控件添加編輯代碼

  在DataGrid標簽中加入
  OnUpdateCommand=DataGrid_UpdateOnCancelCommand=DataGrid_CancelOnEditCommand=DataGrid_Edit代碼
  在codeBehind頁面加入如下代碼
  ///響應編輯按鈕
  publicvoidDataGrid_Edit(ObjectsenderDataGridCommandEventArgse)
  {
   DataGridEditItemIndex=eItemItemIndex;
   if(RequestQueryStringGet(classID)!=null)
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
   else
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));
  }
  
  ///響應取消按鈕
  publicvoidDataGrid_Cancel(ObjectsenderDataGridCommandEventArgse)
  {
   DataGridEditItemIndex=;
   if(RequestQueryStringGet(classID)!=null)
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
   else
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));

  }
  
  ///響應更新按鈕  
  publicvoidDataGrid_Update(ObjectsenderDataGridCommandEventArgse)
  {
   TextBoxClassNameText=(TextBox)eItemCells[]Controls[];
   stringclassName=ClassNameTextText;
   intclassID=IntParse((eItemCells[]Text)ToString());
   TextBoxorderID=(TextBox)eItemCells[]Controls[];
   intorderID=IntParse(orderIDText);
   ActorClassModifyActorClass(classNameclassIDorderID);

  DataGridEditItemIndex=;
   if(RequestQueryStringGet(classID)!=null)
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
   else
    CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));
  }

  說明

  ()DataGrid事件處理程序的格式
   MethodName(ObjectsenderDataGridCommandEventArgse)
  ()更新按鈕的說明
   A獲取編輯狀態中的文本框
    TextBoxClassNameText=(TextBox)eItemCells[]Controls[];
    stringclassName=ClassNameTextText;
   B獲取編輯狀態中的下拉列表框
    方法一
    intclassID;
    classID=IntParse(RequestFormGet(sltclassname));
    方法二
    DropDownListbbb=(DropDownList)eItemCells[]FindControl(dpStatus);
    stringddpValue=bbbSelectedValue
   C獲取編輯狀態中的復選框
    boolboolEnabled=((CheckBox)eItemFindControl(chk_enabled))Checked;
    Stringstr;
    if(boolEnabled)
    {
     str=;
    }
    else 
    {
     str=;
    }
    賦值給str原因是插入到數據庫的布爾型值只能是或者
   D獲取編輯狀態中的文本值即該列是只讀的
    stringstoryID=(eItemCells[]Text)ToString();

  為DataGrid控件添加分頁事件

  在DataGrid控件標簽中加入如下代碼
  OnPageIndexChanged=DataGrid_PageIndexChanged
  在後台中加入如下代碼
  ///<summary>
  ///響應分頁事件
  ///</summary>
  ///<paramname=sender></param>
  ///<paramname=e></param>
  publicvoidDataGrid_Page(ObjectsenderDataGridPageChangedEventArgse)
  {
   DataGridCurrentPageIndex=eNewPageIndex;
   DataBind();
  }
 
 為DataGrid控件添加綁定事件即在DataGrid綁定時發生的事件處理

  一般用些事件來做一些頁面上的效果如更改背景色文本框大小等
  OnItemDataBound=DataGrid_ItemDataBound
  ///<summary>
  ///響應DataGrid綁定事件
  ///</summary>
  ///<paramname=sender></param>
  ///<paramname=e></param>
  publicvoidDataGrid_ItemDataBound(objectsenderSystemWebUIWebControlsDataGridItemEventArgse)
  {
   if(eItemItemType==ListItemTypeItem)
   {
    eItemAttributesAdd(onmouseoverthisstylebackgroundColor=#cdafa);
    eItemAttributesAdd(onmouseoutthisstylebackgroundColor=white);

  }
   elseif(eItemItemType==ListItemTypeAlternatingItem)
   {
    eItemAttributesAdd(onmouseoverthisstylebackgroundColor=#cdafa);
    eItemAttributesAdd(onmouseoutthisstylebackgroundColor=#fff);
   }
  }
  
 為DataGrid控件添加接鈕處理事件程序

  在DataGrid控件標簽中加入如下代碼
  OnItemCommand=ItemsGrid_Command
  在後台中加入如下代碼
  publicvoidItemsGrid_Command(ObjectsenderDataGridCommandEventArgse)
  {
   switch(((LinkButton)eCommandSource)CommandName)
   {

  caseDelete:
     intclassID=IntParse((eItemCells[]Text)ToString());
     ActorClassDeleteActorClass(classID);
     if(RequestQueryStringGet(classID)!=null)
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
     else
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));
     break;

  //AddothercaseshereiftherearemultipleButtonColumnsin
     //theDataGridcontrol
    casehidden:
     intactorID=IntParse((eItemCells[]Text)ToString());
     ActorClassHiddenActorClass(actorID);
     if(RequestQueryStringGet(classID)!=null)
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
     else
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));
     break;
    caseMoveUp:
     intactorclassID=IntParse((eItemCells[]Text)ToString());
     stringorderID=(eItemCells[]Text)ToString();
     ActorClassMoveUp(orderIDactorclassID);
     if(RequestQueryStringGet(classID)!=null)
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
     else
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbydepthorderIDdesc));
     break;
    caseMoveDown:
     actorclassID=IntParse((eItemCells[]Text)ToString());
     orderID=(eItemCells[]Text)ToString();
     ActorClassMoveDown(orderIDactorclassID);
     if(RequestQueryStringGet(classID)!=null)
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswhereparentID=+RequestQueryStringGet(classID)+orderbydepthorderIDdesc));
     else
      CommonBindData(DataGridCommonGetSource(select*fromActorClasswheredepth=orderbyorderID));
     break;
    

  default:
     //Donothing
     break;

  }
  }

  為DataGrid添加模板列但是內容根據字段值來顯示鏈接還是文本

  以下三個都是根據字段列不同而顯示內容及顯示控件不同的處理代碼
  <asp:TemplateColumnHeaderText=子菜單>
   <ItemTemplate>
    <%#ActorClassManagehasLeaf(DataBinderEval(ContainerDataItemActorClassID)ToString()DataBinderEval(ContainerDataItemchild)ToString())%>
   </ItemTemplate>
  </asp:TemplateColumn>
  publicstaticstringhasLeaf(stringidstringchild)
  {
   stringlRtn=;
   if(IntParse(child)>)
    lRtn=<a+id+><fontcolor=blue>子菜單(+child+)</font></a>;
   else
    lRtn=無子菜單;

  returnlRtn;
  }
  <asp:TemplateColumnHeaderText=屬性>
   <ItemTemplate>
    <asp:LinkButtonText=<%#IsHidden(DataBinderEval(ContainerDataItemActorClassID)ToString()(bool)DataBinderEval(ContainerDataItemEnabled))%>runat=serverCommandName=hiddenID=Linkbutton></asp:LinkButton>
   </ItemTemplate>
  </asp:TemplateColumn>
  publicstaticstringIsHidden(stringidboolenabled)
  {
   stringlRtn=;
   if(enabled==true)
   {
    lRtn=[顯示];
   }
   else
   {
    lRtn=隱藏;
   }
   returnlRtn;
  }
  publicstaticvoidSort(stringactorclassIDstringorderID)
  {
   stringtemp=;
   if(IntParse(BgPicManageGetMaxCode(actorclassorderID))==IntParse(orderID))
   {
    temp+=<ipnuttype=submitvalue=向下移>;
   }
   if(IntParse(orderID)==)
   {
    temp+=<ipnuttype=submitvalue=向上移>;
   }
  }
  
DataGrid控件自定義分頁代碼
 
  將下列代碼放於包含<DataGrid>的form中去
  <palign=center>
         <asp:labelid=lblPageCountrunat=server></asp:label>
         <asp:labelid=lblCurrentIndexrunat=server></asp:label>
         <asp:linkbuttonid=btnFirstonclick=PagerButtonClickrunat=serverFontName=verdana
          Fontsize=ptForeColor=navyCommandArgument=></asp:linkbutton>
         <asp:linkbuttonid=btnPrevonclick=PagerButtonClickrunat=serverFontName=verdana
          Fontsize=ptForeColor=navyCommandArgument=prev></asp:linkbutton>
         <asp:linkbuttonid=btnNextonclick=PagerButtonClickrunat=serverFontName=verdana
          Fontsize=ptForeColor=navyCommandArgument=next></asp:linkbutton>
         <asp:linkbuttonid=btnLastonclick=PagerButtonClickrunat=serverFontName=verdana
          Fontsize=ptForeColor=navyCommandArgument=last></asp:linkbutton>
       </p>
       
       後台代碼
       
       privatevoidPage_Load(objectsenderSystemEventArgse)
       {
         //在此處放置用戶代碼以初始化頁面
         btnFirstText=最首頁;
         btnPrevText=前一頁;
         btnNextText=下一頁;
         btnLastText=最後頁;
         //綁定數據源
         if(!PageIsPostBack)
         {
          OpenDatabase();
          BindGrid();
         }
       }
       
       //用於顯示第幾頁總*頁
       privatevoidShowStats()
  {
    lblCurrentIndexText=+(MyDataGridCurrentPageIndex+)ToString()+;
    lblPageCountText=總共+MyDataGridPageCountToString()+;
  }
  
  //響應分頁按鈕
  publicvoidPagerButtonClick(objectsenderEventArgse)
       {
        stringarg=((LinkButton)sender)CommandArgumentToString();
         switch(arg)
         {
           casenext:
             if(MyDataGridCurrentPageIndex<(MyDataGridPageCount))
             {
              MyDataGridCurrentPageIndex+=;
            }
            break;
           caseprev:
             if(MyDataGridCurrentPageIndex>)
             {
              MyDataGridCurrentPageIndex=;
             }
             break;
           caselast:
             MyDataGridCurrentPageIndex=(MyDataGridPageCount);
             break;
           default:
             MyDataGridCurrentPageIndex=SystemConvertToInt(arg);
             break;
         }
         BindGrid();
         ShowStats();
       }


From:http://tw.wingwit.com/Article/program/net/201311/12340.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.