控件用法参考:GridView的用法大全

GridView控件使用经验2007年12月05日 星期三 下午 12:47GridView控件是Asp.net 1.1版本流行控件DataGrid的继承者,功能比DataGrid增强不少,但是也有很大的不同啊。将最近使用这个控件的经验同各位同学分享如下:

   1).掩藏字段的处理:
    DataGrid可以将字段直接设置为Visible=false,可以通过Cell[x].Text取到值。 GridView这个功能失效了,可以使用运行时来设定该列为掩藏。处理RowDataBound事件。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   e.Row.Cells[
5].Visible = false;
}

  2).获取所选列的数据:
    DataGrid可以直接通过所选行来获取,GridView同样的代码无法运行。GridView 可以通过GridViewRow来获取。BtnAudit是模版列中的按钮。
GridViewRow grdRow = (GridViewRow)btnAudit.Parent.Parent;
string strId = grdRow.Cells[0].Text;
string memberId = grdRow.Cells[5].Text;

   3).最终删除一条数据之前进行确认,这个可以使用摸版列,在摸版列中放置按钮控件,其中有一个客户端事件onclientclick,这里可以写确认处理javascript脚本.例如:
             <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btnRefuse" runat="server" OnClick="btnRefuse_Click" Text="拒绝" OnClientClick="return confirm(' 你真的要拒绝这个用户加入俱乐部?')"/>
                </ItemTemplate>
            </asp:TemplateField>
           
前言:在我们做WEB开发的过程中,经常会遇到GridView中的某些字段太长了,如果全部显示出来就会使排版混,影响美观,尤其是在我们做新闻系统时肯定会遇到,比如显示新闻列表的gridview,页面的版面已设计美观,但是有的新闻标题过长,我们希望只显示一定长度,后面加省略号,然后当鼠标移上去时再显示标题的全部内容,这样就即做到了不影响版面的布局,又做到了标题内容的全部显示.
 下图是我做的规则显示的效果图,有些规则太长,我要做到的是,当标题超出一定长度时我加省略号,当标题在一定长度范围内时,全标题显示: 
效果如上,那么这种效果我们如何实现呢?,在GridView绑定的时候要做什么工作?
    
    
接下来我们来看实现思路:其实说起来很简单,我们在这里将采用模板列,在模版列里拖入一个label控件来进行数据绑定,它的text属性绑定的时候用一个条件表达式来判断是全部绑定标题文字还是只绑定部分标题文字+省略号;它的tooltip属性就直接绑定标题字段,这样我们的鼠标移上去就可以显示标题的全部内容了,绑定代码如下:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RuleId" Width="100%" ShowHeader="False" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemStyle Width="60px" />
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Green" Text='<%# Eval("RuleOrder") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="规则标题">
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" CssClass="grid1" Height="20px" />
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("HtmlPath") %>' ToolTip='<%Eval("RuleTitle")%>'
Text='
<%Eval("RuleTitle").ToString().Length>16?Eval("RuleTitle").ToString().Substring(0,16)+"":Eval("RuleTitle"%>' Font-Bold="True"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

从上面的代码可以看出,我绑定Label控件的Text属性的时候用了条件表达式,当数据库中的标题长度大于16时,则截取前16个字符加上省略号进行显示,当小于16时,就全部绑定.ToolTip属性直接帮定标题字段,鼠标移上去就可显示全部标题了。(题外话,如果你作的是新闻发布系统,你也可以在Text属性的后面再加上一个发布日期的绑定字段,这样标题,日期全出来聊,呵呵,可以灵活应用,举一反三)
gridview添加删除确认对话框

方法一:

VB代码

Protected Sub GridView1_RowDataBound(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
          
If e.Row.RowType = DataControlRowType.DataRow Then
              e.Row.Cells(
12).Attributes.Add("onclick""return confirm('你确认要删除吗?')")
          
End If
      
End Sub


C#代码

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)
          {
              e.Row.Cells[
5].Attributes.Add("onclick""return confirm('你确认要编辑吗?')");

          }
}

方法二

在VS2005提供的GridView中我们可以直接添加一个CommandField删除列:<asp:CommandField ShowDeleteButton="True" />,然后在GridView的OnRowDeleting事件中完成删除。但一般情况下我们在做这种删除操作时都需要先让用户确认一下,然后后再删除记录,以避免误操作引起的误删除。

那我们可以通过下面方法给GridView删除前加上一个确认对话框。

首先,在GridView的属性对框话框中点击“Columns”进入它的"字段"设计器;或者在设计窗口直接点击GridView控件右上角的那个小箭头,点击"编辑列",进入"字段"设计器。

接着在"字段"设计器中的左下方"选定的字段"框中,选择以前已加上的那个CommandField“删除”列,这时在右边它的属性列表下会看到一个"将此它段转换为 TemplateFied"的项,点击将它转换为TemplateFied列。

然后退出"字段"设计器,切换到源码视图你会发现该列已由原来的:
<asp:CommandField ShowDeleteButton="True" />
变为了:

<asp:TemplateField ShowHeader="False">
                                  
<ItemTemplate>
                                      
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"

CommandName
="Delete"    Text="删除"></asp:LinkButton>
</ItemTemplate>

最后在<asp:LinkButton>中加入:OnClientClick="return confirm('您确认删除该记录吗?');"

这样点击删除时就会先在客户端弹出“您确认删除该记录吗?”对话框,点击"确定",则进行删除;点击"取消",则不删除.
而原来在onRowDeleting事件中写的代码完全不用改变。鼠标在GridView上移动时变换颜色

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
          
{
              
if (e.Row.RowType == DataControlRowType.DataRow )
              
{
                  e.Row.Attributes.Add(
"onmouseover""currentcolor=this.style.backgroundColor;this.style.backgroundColor='#C0C0FF';this.style.cursor='hand';");
                  
//当鼠标移走时还原该行的背景色
                  e.Row.Attributes.Add("onmouseout""this.style.backgroundColor=currentcolor");
              }

          }

RowCreated:开被创建时发生
e.Row.RowType == DataControlRowType.DataRow 判断是否是数据行
DataControlRowType的枚举有:
DataRow数据行
EmptyDataRow
Footer
Header
Pager
Separator
如果对单元格进行变换。

if (e.Row.Cells[8].Text == "USA")
               
{
                   
//e.Row.BackColor = System.Drawing.Color.Red; //修改整行的颜色
                   e.Row.Cells[8].BackColor = System.Drawing.Color.Red;     //修改单元格的颜色(第9列)
               }

不足。前端页面代码过多。站带宽。
 在GridView的第一列使用CheckBox控制每一行数据,是经常使用的,这里面我要记录的是全选、全消、选中行的底色更改,还有就是在提交数据的时候,取选中的行的编号等功能

aspx页面定义:

<asp:GridView ID="GridView1" runat="server">
         
<Columns>
             
<asp:TemplateField ShowHeader="False" HeaderText="选择">
                 
<ItemStyle Width="60px" Wrap="False" />
                 
<HeaderTemplate>
                     
<asp:CheckBox ID="CheckBox1" runat="server"></asp:CheckBox>
                 
</HeaderTemplate>
                 
<ItemTemplate>
                     
<asp:CheckBox ID="CheckBox1" runat="server"></asp:CheckBox>
                     
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("EventID") %>' Visible="false"></asp:TextBox>
                 
</ItemTemplate>
             
</asp:TemplateField>
         
</Columns>
        
<HeaderStyle Font-Bold="False" BackColor="#EEEEEE" />
         
<AlternatingRowStyle BackColor="#EEEEEE" />
</asp:GridView>

这样在GridView的第一列,是CheckBox控件,在HeaderTemplate里的是用来控制全选全消的,在TemplateField里的,用来控制当前行是不是选中行

js脚本是这个:

<script type="text/javascript" language="javascript">
function changecolor(obj,color)
{
    e 
= event.srcElement
    
if(e.checked==true)
    
{
      e 
= e.parentElement
      e.style.background 
= "#C0C0FF"
     }

     
else
     
{
       e 
= e.parentElement
       e.style.background 
= color
      }

}


function CheckSelect(del)
{
     
var rt=true;
     
var num=0;
     
var boxorder=0;
     
var objCheckBox;
     
for(var i=0;i<aspnetForm.length;i++)
     
{
         
///alert(aspnetForm.elements[i].type);
         if(aspnetForm.elements[i].type=="checkbox")
         
{
             boxorder
++;
             objCheckBox
=aspnetForm.elements[i];
             
///alert(objCheckBox.checked);
             if(objCheckBox.checked)
             
{
                 
if(boxorder>1)
                 
{
                     
//如果是第一个CheckBox,是用来全选全消的,这个不算,不用自加
                     num++;
                 }

             }

         }

     }

     
///alert(num);
     if(!del)
     
{
         
if(num>1)
         
{
             alert(
"此操作不允许选择多个事件");
             rt
=false;
         }

     }

     
if(num==0)
     
{
         alert(
"此操作要求先选择一个事件");
         rt
=false
     }

     
///alert(rt);
     return rt;
}


function SelectAll(sa)
{
     
///全选/全消
     var objCheckBox;
     
for(var i=0;i<aspnetForm.length;i++)
     
{
         
if(aspnetForm.elements[i].type=="checkbox")
         
{
             objCheckBox
=aspnetForm.elements[i];
             objCheckBox.checked
=sa;
         }

     }

}

</script>


第一个函数changecolor用来控制被选择的行的颜色突出,第二个函数CheckSelect用来判断现在有几个行被选中,第三个函数SelectAll用来控制全选全消

在cs页面里,为每一行的CheckBox绑定客户端事件:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
     
{
         
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
         
{
             CheckBox mycb 
= new CheckBox();
             mycb 
= (CheckBox)e.Row.FindControl("CheckBox1");
             
if (mycb != null)
             
{
                 
if (e.Row.RowType == DataControlRowType.DataRow)
                 
{
                    
if (e.Row.RowIndex % 2 == 0)
                     
{
                         mycb.Attributes.Add(
"onclick""changecolor(this.name,'#FFFFFF')");
                     }

                     
else
                     
{
                         mycb.Attributes.Add(
"onclick""changecolor(this.name,'#EEEEEE')");
                     }

                 }

                 
else if (e.Row.RowType == DataControlRowType.Header)
                 
{
                     mycb.Attributes.Add(
"onclick""SelectAll(this.checked)");
                 }

             }

         }

     }


这里,对不同的DataControlRowType,我绑定了不同的客户端事件,因为定义在HeaderTemplate和ItemTemplate里的CheckBox是要执行不同的客户端事件的

上面的东西都很简单,分清楚客户端和服务器端就可以了,我一开始的时候在服务器端和客户端跳来跳去,自己都乱了,好烦啊

我在这里还要记录这样的情况:

在页面里,有一个自定义用户控件,有一个GridView控件,在自定义用户控件里,有Button用来控制GridView里的记录

我要记录的是,怎么在这个Button里,判断有哪些记录被选中

1、上面的aspx代码里,我加了TextBox,记录编号

2、在自定义用户控件里,用下面的事件,就返回选中行的编号了

public string GetEid()
     
{
         
//取选中的事件编号
         string streid = "";
         GridView mygv 
= new GridView();
         mygv 
= (GridView)Parent.FindControl("GridView1");
         
if (mygv != null)
         
{
             
int i, row;
             i 
= 0;
             row 
= mygv.Rows.Count;
             CheckBox mycb 
= new CheckBox();
             
for (i = 0; i < row; i++)
             
{
                 mycb 
= (CheckBox)mygv.Rows[i].FindControl("CheckBox1");
                 
if (mycb != null)
                 
{
                     
if (mycb.Checked)
                     
{
                         TextBox mytb 
= new TextBox();
                         mytb 
= (TextBox)mygv.Rows[i].FindControl("TextBox1");
                         
if (mytb != null)
                         
{
                             streid 
= streid + mytb.Text.Trim() + ",";
                         }

                     }

                 }

             }

         }

         
if (streid.Length > 0)
         
{
             streid 
= streid.Remove(streid.Length - 1);
         }

         
return streid;
     }

就是Parent和FindControl的使用,用Parent可以引用包含自定义用户控件的页面,对这个页面里的GridView的每一行扫描,就可以取到每一行的CheckBox了

对自定义控件里,如果有的Button需要先选择一个 or 多个记录才允许操作的,可以在自定义控件里给Button加上客户端事件

protected void Page_Load(object sender, EventArgs e)
     
{
         Button1.Attributes[
"onclick"= "return CheckSelect(false);";
         Button4.Attributes[
"onclick"= "return CheckSelect(false);";
         Button2.Attributes[
"onclick"= "return CheckSelect(true);";
     }

这里我给Button1和Button4加了不允许多个选择的事件,给Button2加了允许多个选择的事件

原文地址:https://www.cnblogs.com/Dlonghow/p/1223514.html