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、停留在某一行变色
PRivatevoidChangeColor(objectsender, 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、操作某一行
直接举例说明
protectedvoidgvSubjectiveOption_RowCommand(objectsender, GridViewCommandEventArgs e)
{introwSelected =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;//选项附件stringoptionaccessoryStr =questionOptionInfo.QO_Accessory;string[] optionAccessoryArr = optionAccessoryStr.Split(',');for(inti =0; i < optionAccessoryArr.Length; i++)
{
OptionAccessoryList.Add(optionAccessoryArr[i]);
}
BindOptionAccessoryList();
}if(e.CommandName =="DeleteOption")
{
QuestionOptionBLL.Delete(rowSelected);intEQ_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>privatevoidInitializeCheckBox(GridView gv, DataTable dtSource,stringcbName,stringcbValue)
{intcount =dtSource.Rows.Count;if(count >0)
{for(inti =0; i < count; i++)
{
CheckBox cb= gv.Rows[i].FindControl(cbName)asCheckBox;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>条 当前: 第<font color='blue'>%CurrentPageIndex%</font> 页,共 <font color='blue'>%PageCount%</font>页"CurrentPageButtonPosition="Beginning"onpagechanged="AspNetPager1_PageChanged"></webdiyer:AspNetPager>
</div>
后台添加逻辑:this.AspNetPager1.RecordCount = ExamQuestionInfoList.Count;
同时事件:
protectedvoidAspNetPager1_PageChanged(objectsender, EventArgs e)
{this.gvQuestions.PageIndex =this.AspNetPager1.CurrentPageIndex -1;this.gvQuestions.SelectedIndex = -1;//更新成功后更新界面BindgvQuestions();
}
如果gridview中的记录很少,可能一两页就能解决问题,那自带分页完成能解决问题:
onpageindexchanging="gvObjectOption_PageIndexChanging"
protectedvoidgvObjectOption_PageIndexChanging(objectsender, GridViewPageEventArgs e)
{this.gvObjectOption.PageIndex =e.NewPageIndex;this.gvObjectOption.DataBind();
}
分页到此完成。
2014年9月1日添加:
此处添加asp.net的gridview自带的编辑、更新、取消事件。比较简单,直接贴代码:
protectedvoidgvExamQuestions_RowEditing(objectsender, GridViewEditEventArgs e)
{
gvExamQuestions.EditIndex=e.NewEditIndex;BindgvExamQuestion(E_ID);//重新绑定}///<summary>///取消编辑事件///</summary>///<param name="sender"></param>///<param name="e"></param>protectedvoidgvExamQuestions_RowCancelingEdit(objectsender, GridViewCancelEditEventArgs e)
{
gvExamQuestions.EditIndex= -1;BindgvExamQuestion(E_ID);//重新绑定}///<summary>///更新事件///</summary>///<param name="sender"></param>///<param name="e"></param>protectedvoidgvExamQuestions_RowUpdating(objectsender, 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 voidBindDropDownUp()
{
ArrayList al = newArrayList();
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 voidBindDropDownUp()
{
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;
}
总结到此,如果另有积累,再另行添加。