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 = ;
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 = ; 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 > )
{
for (int i = ; i < count; i++)
{
CheckBox cb = gv.Rows[i].FindControl(cbName) as CheckBox; if (cb != null)
{
if (dtSource.Rows[i][cbValue].ToString() == "")
{
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 =""
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;
同时事件:
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
this.gvQuestions.PageIndex = this.AspNetPager1.CurrentPageIndex - ;
this.gvQuestions.SelectedIndex = -;
//更新成功后更新界面
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 = -;
BindgvExamQuestion(E_ID);//重新绑定
} /// <summary>
/// 更新事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvExamQuestions_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//此处可以进行逻辑操作 gvExamQuestions.EditIndex = -;
BindgvExamQuestion(E_ID);//重新绑定
}
WPF中gridview使用
很久不做wpf项目了,今天做wpf时需要使用gridview控件,想到前段时间asp.net中总结过gridview控件,所以拿来使用,发现完全不同。没办法,忘记了,查找很久才找到以前代码,并记录,以便下次查找。
最主要的是xaml中gridview列表的排布以及样式的自定义。
<DataGrid AutoGenerateColumns="False" Grid.Column="" Grid.Row="" FontSize="" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" HorizontalGridLinesBrush="White" RowBackground="Black" Foreground="White" RowHeight="" Background="Black" ColumnHeaderHeight="" Height="" HorizontalAlignment="Left" Margin="598,151,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="" 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="" />
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
</DataGrid.ColumnHeaderStyle> <DataGrid.Columns >
<DataGridTextColumn Header="考号" Width="" Binding="{Binding Path=user_ID}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="成绩" Width="" Binding="{Binding Path=Score}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="项目" Width="" Binding="{Binding Path=Curriculum}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="考核时间" Width="" Binding="{Binding Path=ExamTime}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="耗时" Width="" Binding="{Binding Path=TimeElapsed}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="答题数" Width="" Binding="{Binding Path=AllQuestionNUM}" IsReadOnly="True" ElementStyle="{StaticResource dgCell}"/>
<DataGridTextColumn Header="答对数" Width="" 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;
}
总结到此,如果另有积累,再另行添加。
GridView的常规用法的更多相关文章
- mapreduce的cleanUp和setUp的特殊用法(TopN问题)和常规用法
一:特殊用法 我们上来不讲普通用法,普通用法放到最后.我们来谈一谈特殊用法,了解这一用法,让你的mapreduce编程能力提高一个档次,毫不夸张!!!扯淡了,让我们进入正题: 我们知道reduce和m ...
- 【python】-matplotlib.pylab常规用法
目的: 了解matplotlib.pylab常规用法 示例 import matplotlib.pylab as pl x = range(10) y = [i * i for i in x] pl. ...
- MarkDown的常规用法
MarkDown的常规用法 标题 # 一级标题 ## 二级标题 ... ###### 六级标题 列表 第二级 - 和 空格 + 和 空额 * 和 空格 第三级 代码块 多行代码块 3个` 回车 单行代 ...
- GridView的详细用法
l GridView无代码分页排序 l GridView选中,编辑,取消,删除 l GridView正反双向排序 l GridView和下拉菜单DropDownList结合 l GridView和Ch ...
- 刚刚开通博客,分享Asp.Net的GridView的基本用法
包含有 数据的编辑,删除, 标题的添加,自定义分页,高亮显示鼠标所在,以及数据不足时添加空行 aspx页面代码 <asp:GridView ID="GridView1" ru ...
- C# 当中 LINQ 的常规用法(Lambda 方式)
仅以本篇博文记录 LINQ 相关操作的基本知识,原型参考自 MSDN 相关知识,中间加以自己的理解与 DEMO. 1. IEnuemrable<T>.Select() Select 方法比 ...
- SimpleAdapter与listview,gridview的组合用法
首先要明白SimpleAdapter构造方法的几个参数的含义: public SimpleAdapter(Context context, List<? extends Map<Strin ...
- Vuex 常规用法
背景 很多时候我们已经熟悉了框架的运用,但是有时候就是忘了怎么用 所以这里想记下大部分的框架使用方法,方便使用的时候拷贝 一.安装 npm 方式 npm install vuex --save yar ...
- iOS -Swift 3.0 -String(字符串常规用法)
// // ViewController.swift // Swift-String // // Created by luorende on 16/9/10. // Copyright © 2016 ...
随机推荐
- centos下yum搭建安装linux+apache+mysql+php环境
一.脚本YUM源安装: 1.yum install wget #安装下载工具wget 2.wge ...
- Django WSGI Error:class.__dict__ not accessible in restricted mode
一.问题 今天网站出了一个错误: RuntimeError at /index.html class.__dict__ not accessible in restricted mode 二.原因 用 ...
- ZBrush中如何才能快速完成脸部雕刻(下)
骨骼,是一门基础艺术,几百年来一直为伟大的艺术大师所研究,它曾经,也将一直是创作现实且可信角色的关键,提高骨骼知识更将大大提高雕刻技能. 查看更多内容请直接前往:http://www.zbrush ...
- 给定一个整数实现奇偶bit位互换
1.分别取出所有奇数bit位和偶数bit位 0x55555555(对应二进制奇数bit位为1,偶数bit位全为0)&num 0xaaaaaaaa(对应二进制即偶数bit位为1,奇数bit位全为 ...
- 深入理解maven及应用--转
(一):生命周期和插件 在项目里用了快一年的maven了,最近突然发现maven项目在eclipse中build时非常慢,因为经常用clean install命令来build项目,也没有管那么多,但最 ...
- AndroidStudio权威教程 AS添加第三方库的6种方式(Jar module so等)
点击项目设置按钮 依次选择 App > Dependencies 1. 直接搜索法 依次选择 + > Library dependency 这里的搜索一定要是全名的,不然搜不到哦 下图所表 ...
- 17Mybatis_动态sql-sql片段
这篇文章讲一下sql片段. 讲一下sql片段的的需求: 将上边实现的动态sql判断代码块抽取出来,组成一个sql片段.其它的statement中就可以引用sql片段. 方便程序员进行开发. 第一步我们 ...
- jQuery Mobile和Sencha Touch哪个更适合你?
纯粹的总结一下移动web开发框架,移动web开发框架有jQuery Mobile .Sencha Touch等等,他们都来源于web开发,是成熟的框架,jQuery Mobile出自于jQuery家族 ...
- C语言 百炼成钢15
//题目43:有n个人围成一圈,顺序排号.从第一个人开始报数(从1到3报数),凡报到3的人退出 //圈子,问最后留下的是原来第几号的那位. #include<stdio.h> #inclu ...
- 加密算法使用(三):用用BASE64
采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到 package testEncrypt; import java.security.Key; import java.secu ...