GridView的常規用法


  GridView控件在Asp.net中相當常用,以下是控件的解釋,有些是常用的,有些是偶爾用到的,查找、使用、記錄,僅此而已。(最后附帶DropDownList控件)

 

ASP.NET中GridView常規用法

  1、gridview前台界面代碼

  gridview創建列最主要的有兩種方式:

  1)數據綁定,表示數據綁定控件中作為文本顯示的字段。DataField ="AnswerNum",AnswerNum是數據源中的一個字段。舉例說明: 

<asp:BoundField DataField ="AnswerNum" >
        <ItemStyle Width ="8%" HorizontalAlign ="Center" />
 </asp:BoundField>

  2)使用模板創建,舉例說明: 

<asp:TemplateField HeaderText ="查看">
     <ItemTemplate >
          <asp:LinkButton ID ="LinkButtonViewSOption" runat ="server" CommandName ="ViewSOption" CommandArgument ='<%# Bind("QO_ID") %>'>描</asp:LinkButton>
     </ItemTemplate>
     <ItemStyle Width ="5%" HorizontalAlign ="Center" />
</asp:TemplateField>

   ItemStyle是其模板樣式,根據具體要求做出調整。

  

  2、綁定數據源 

this.gvQuestions.DataSource = ExamQuestionInfoList;
                this.gvQuestions.DataBind();
                this.gvQuestions.PageIndex = 0;

  gvQuestions為GridView控件,ExamQuestionInfoList為數據源,gridview的數據源可以是DataTable或者是數據集DataSet。

 

  3、停留在某一行變色

private void ChangeColor(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#E6F5FA'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }

protected void gvQuestions_RowDataBound(object sender, GridViewRowEventArgs e)
{
ChangeColor(sender, e);
}

 

  4、操作某一行

  直接舉例說明

protected void gvSubjectiveOption_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowSelected = Convert.ToInt32(e.CommandArgument);
            questionOptionInfo = QuestionOptionBLL.GetModel(rowSelected);

            //查看
            if (e.CommandName == "ViewSOption")
            {
                this.tbOptionStem.Text = questionOptionInfo.QO_Option;
                this.tbCorrectAnswer.Text = questionOptionInfo.QO_SubjectAnswer;//主觀題答案
                this.tbCorrectAnswerExplain.Text = questionOptionInfo.QO_Explain;

                //選項附件
                string optionAccessoryStr = questionOptionInfo.QO_Accessory;
                string[] optionAccessoryArr = optionAccessoryStr.Split(',');
                for (int i = 0; i < optionAccessoryArr.Length; i++)
                {
                    OptionAccessoryList.Add(optionAccessoryArr[i]);
                }
                BindOptionAccessoryList();
            }

            if (e.CommandName == "DeleteOption")
            {
                QuestionOptionBLL.Delete(rowSelected);
                int EQ_ID = questionOptionInfo.EQ_ID;
                BindSubjectiveOption(EQ_ID);//重新綁定主觀題問題信息
            }
        }

  e.CommandName對應前台界面的一些字段: 

<asp:TemplateField HeaderText ="查看">
        <ItemTemplate >
             <asp:LinkButton ID ="LinkButtonViewSOption" runat ="server" CommandName ="ViewSOption" CommandArgument ='<%# Bind("QO_ID") %>'>描</asp:LinkButton>
        </ItemTemplate>
        <ItemStyle Width ="5%" HorizontalAlign ="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText ="刪除" >
       <ItemTemplate >
            <asp:ImageButton ID ="ImageButtonDelete2" runat ="server"  BorderStyle ="None" CommandName ="DeleteOption" CommandArgument ='<%# Bind("QO_ID") %>' ImageUrl ="~/images/delete.gif" />
        </ItemTemplate>
      <ItemStyle Width ="5%" HorizontalAlign ="Center" />
</asp:TemplateField>

  其中CommandName ="DeleteOption" CommandArgument ='<%# Bind("QO_ID") %>代表數據集中的某個字段。

  

  5、添加Checkbox並且初始化台界面:

<asp:TemplateField >
     <ItemTemplate >
         <asp:LinkButton ID ="LinkButton1" runat ="server" CommandName ="selectCorrectAnswer" CommandArgument ='<%# Bind("QO_ID") %>'>
           <asp:CheckBox ID ="cbCorrectAnswer" runat ="server" />
         </asp:LinkButton>
</ItemTemplate>

   后台邏輯: 

/// <summary>
        /// 初始化checkbox值
        /// </summary>
        /// <param name="gv">gridview控件</param>
        /// <param name="dtSource">數據源</param>
        /// <param name="cbName">checkbox控件名稱</param>
        /// <param name="cbValue">checkbox的值</param>
        private void InitializeCheckBox(GridView gv, DataTable dtSource, string cbName, string cbValue)
        {
            int count = dtSource.Rows.Count;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    CheckBox cb = gv.Rows[i].FindControl(cbName) as CheckBox;

                    if (cb != null)
                    {
                        if (dtSource.Rows[i][cbValue].ToString() == "0")
                        {
                            cb.Checked = false;
                        }
                        else
                        {
                            cb.Checked = true;
                        }
                    }
                }
            }
        }

    

  6、去掉gridview自帶的分頁數字

  因為項目中在使用gridview時需要用到分頁,而它本身的分頁顯得不足以表達項目所以表現的操作,所以需要添加新的分頁,必然需要去到它原來的分頁。

  1)首先如果分頁,必然要把屬性AllowPaging設置為true。

  2)PagerSettings-Visible屬性設置為false,分頁數字自此去掉。

  3)手動添加分頁,已經寫出來了,但是項目還沒有測試到,所以等此功能測試完畢后再添加此部分。

  添加手動分頁:

  首先添加引用:<%@ Register Assembly ="AspNetPager" Namespace ="Wuqi.Webdiyer" TagPrefix ="webdiyer" %>

  寫前台界面:

<div id ="PagingDiv" style ="text-align:center ;vertical-align:middle;margin-top:4px" runat="server">
                                    <webdiyer:AspNetPager ID ="AspNetPager1" runat ="server" 
                                        AlwaysShowFirstLastPageNumber ="true" FirstPageText ="首頁" LastPageText ="尾頁"
                                    NextPageText ="下一頁" PrevPageText ="上一頁" ScrollBars ="Auto" 
                                    ShowCustomInfoSection="Left" ShowPageIndexBox ="Always" AlwaysShow ="true" PageSize ="20" 
                       CustomInfoHTML="總記錄數:<font color='#f30f30'>%RecordCount%</font>條&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;當前: 第<font color='blue'>%CurrentPageIndex%</font> 頁,共 <font color='blue'>%PageCount%</font>頁" 
                                        CurrentPageButtonPosition ="Beginning" onpagechanged="AspNetPager1_PageChanged"></webdiyer:AspNetPager>
                                </div> 

  后台添加邏輯:this.AspNetPager1.RecordCount = ExamQuestionInfoList.Count;

  同時事件: 

protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            this.gvQuestions.PageIndex = this.AspNetPager1.CurrentPageIndex - 1;
            this.gvQuestions.SelectedIndex = -1;
            //更新成功后更新界面
           BindgvQuestions();
        }

 

  如果gridview中的記錄很少,可能一兩頁就能解決問題,那自帶分頁完成能解決問題:

  onpageindexchanging="gvObjectOption_PageIndexChanging"

protected void gvObjectOption_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvObjectOption.PageIndex = e.NewPageIndex;
            this.gvObjectOption.DataBind();
        }

  分頁到此完成。

 

2014年9月1日添加:

此處添加asp.net的gridview自帶的編輯、更新、取消事件。比較簡單,直接貼代碼:

protected void gvExamQuestions_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvExamQuestions.EditIndex = e.NewEditIndex;
            BindgvExamQuestion(E_ID);//重新綁定
        }

        /// <summary>
        /// 取消編輯事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvExamQuestions_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvExamQuestions.EditIndex = -1;
            BindgvExamQuestion(E_ID);//重新綁定
        }

        /// <summary>
        /// 更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvExamQuestions_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
                //此處可以進行邏輯操作

                gvExamQuestions.EditIndex = -1;
                BindgvExamQuestion(E_ID);//重新綁定            
        }

 

 

 WPF中gridview使用

  很久不做wpf項目了,今天做wpf時需要使用gridview控件,想到前段時間asp.net中總結過gridview控件,所以拿來使用,發現完全不同。沒辦法,忘記了,查找很久才找到以前代碼,並記錄,以便下次查找。

  最主要的是xaml中gridview列表的排布以及樣式的自定義。

<DataGrid AutoGenerateColumns="False" Grid.Column="1" Grid.Row="1" FontSize="18" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"  HorizontalGridLinesBrush="White"  RowBackground="Black" Foreground="White" RowHeight="45"  Background="Black"  ColumnHeaderHeight="50"  Height="528" HorizontalAlignment="Left" Margin="598,151,0,0" Name="dataGrid1" VerticalAlignment="Top"  Width="612" AllowDrop="False" FontStretch="Normal" FontStyle="Normal" FontWeight="Normal">
                            <DataGrid.ColumnHeaderStyle>
                                <Style TargetType="DataGridColumnHeader">
                                    <Setter Property="Background" Value="black"/>   
                                    <Setter Property="Foreground" Value="white"/>
                                    <Setter Property="FontSize" Value="20" />
                                    <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                    <Setter Property="VerticalContentAlignment" Value="Center"/>
                                </Style>
                            </DataGrid.ColumnHeaderStyle>

                            <DataGrid.Columns >
                    <DataGridTextColumn Header="考號" Width="60" Binding="{Binding Path=user_ID}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="成績" Width="50" Binding="{Binding Path=Score}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="項目" Width="50" Binding="{Binding Path=Curriculum}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="考核時間" Width="145" Binding="{Binding Path=ExamTime}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="耗時" Width="50" Binding="{Binding Path=TimeElapsed}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="答題數" Width="65" Binding="{Binding Path=AllQuestionNUM}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="答對數" Width="65" Binding="{Binding Path=correctQuestionNUM}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                                <DataGridTextColumn Header="所有試題" Width="*" Binding="{Binding Path=AllQuestion}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
                </DataGrid.Columns >
            </DataGrid >

  上面是一次完整的gridview的使用,其中靜態資源dgCell:

<Page.Resources >
        <ResourceDictionary >
            <Style x:Key="dgCell" TargetType="TextBlock">
                <Setter Property="TextAlignment" Value="Center"/>
            </Style >
        </ResourceDictionary >
    </Page.Resources >

  當然,最后的gridview數據源的綁定則是最簡單的,一行代碼:this.dataGrid1.ItemsSource = transcript.selectScore().Tables[0].DefaultView;

 

 

DropDownList常規用法:

  1、DropDownList綁定簡單數據源

  此處暫且寫一個簡單的數據源,只是為了說明效果。

private void BindDropDownUp()
        {
            ArrayList al = new ArrayList(); al.Add("11"); al.Add("22"); al.Add("33"); this.DropDownList1.DataSource = al; this.DropDownList1.DataBind(); }

  獲取DropDownList中選擇的值:string text = this.DropDownList1.SelectedItem.Text;

 

  2、DropDownList綁定較為復雜數據源

  此處從數據庫中提取一個數據集ds,DropDownList控件的text框中顯示一個值,選中后在后台可以獲取綁定的value。具體如下:

private void BindDropDownUp()
        {
            string strSql = "select * from [OSCE].[dbo].[QuestionType]"; DataSet ds = Query(strSql); this.DropDownList1.DataSource = ds; this.DropDownList1.DataTextField = "QT_Name"; this.DropDownList1.DataValueField = "QT_ID"; this.DropDownList1.DataBind();//將數據源綁定到類似( GridView) 控件 }

  獲取DropDownList控件text框的值:string text = this.DropDownList1.SelectedItem.Text;

  獲取DropDownList控件綁定的value值:string text2 = this.DropDownList1.SelectedValue;

 

  3、在頁面初始化時直接給DropDownList賦值

  題外話:這個功能用的非常多,實現也很簡單,但前提是你必須知道。找了好久才發現的。

ListItem li = DropDownList1.Items.FindByText("外科");//外科是想顯現的值,前提是DataTextField中必須有
            if (li != null)
            {
                int index = DropDownList1.Items.IndexOf(li); DropDownList1.SelectedIndex = index; }

 

  

  總結到此,如果另有積累,再另行添加。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM