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 ...
随机推荐
- HTML5 datalist 标签
以前需要用JS写一个自动完成组件(Suggest),很费劲.HTML5时代则不用了,直接使用datalist标签,直接减少了工作量.如下 <!DOCTYPE html> <html& ...
- 解决ubuntu sudo not found command的问题
将/etc/sudoers 中Defaults env_reset改成Defaults !env_reset取消掉对PATH变量的重置, 然后在/etc/bash.bashrc中最后添加alias s ...
- db2 常用命令(二)
1. 打开命令行窗口 #db2cmd 2. 打开控制中心 # db2cmd db2cc 3. 打开命令编辑器 db2cmd db2ce ======脚本文件操作命令======= -- 执行脚本 ...
- cri-o 创建非infra容器
1.// cri-o/server/container.go // CreateContainer creates a new container in specified PodSandbox fu ...
- [cb] Assetbundle打包(一)
一.简介 Unity的Assetbundle是Unity Pro提供的功能. 理解:Asset 资源,资产:Bundle :包,一批,捆:字面上的意思,就是把资源打包. 在项目中怎么使用Assetbu ...
- maven总结2
依赖 maven版本:apache-maven-3.1.1 IDE: springsource 默认支持maven集成 若使用的是eclipse,则需要先安装m2ec ...
- SVN--分支、合并
首先说下为什么我们需要用到分支-合并.比如项目demo下有两个小组,svn下有一个trunk版.由于客户需求突然变化,导致项目需要做较大改动,此时项目组决定由小组1继续完成原来正进行到一半的工作[某个 ...
- java 13-4 Integer和String、int之间的转换,进制转换
1.int类型和String类型的相互转换 A.int -- String 推荐用: public static String valueOf(int i) 返回 int 参数的字符串表示形式. B. ...
- Ubuntu 下安装 apt-get install npm 失败的解决方案
Ubuntu 下安装 apt-get install npm 失败的解决方案: sudo apt-get remove nodejs npm ## remove existing nodejs an ...
- WPF:如何为程序添加splashScreen(初始屏幕)
原文:http://www.cnblogs.com/chenxizhang/archive/2010/03/25/1694606.html 官网: https://msdn.microsoft.com ...