GridView使用总结

本文介绍GridView控件的多种实用技巧,包括取模板Button对应的行数据、添加删除确认对话框、自动生成数据编号、保存所有数据到Excel、添加标题、点击LinkButton传值、处理超长字符串、显示统计数据、嵌套GridView等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.可以取GridView中模板Button 对应的行的数据

 Dim b1 As Button = CType(sender, Button)
 
Dim cell1 As DataControlFieldCell = CType(b1.Parent, DataControlFieldCell)
 
Dim row1 As GridViewRow = CType(cell1.Parent, GridViewRow)
 
Dim FileName As String = row1.Cells(7).Text

 

二.添加GridView删除确认对话框

Protected Sub gdvUploadfile_RowDataBound(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvUploadfile.RowDataBound        
        
If e.Row.RowType = DataControlRowType.DataRow Then
            
'return后面一定要有空格,否则跳不出来
            Dim btnDelete1 As Button = CType(e.Row.FindControl("btnDelete"), Button)
            btnDelete1.Attributes.Add(
"onclick""javascript:return " + "confirm('Are you sure you want to delete this data')"
     
End If
    
End Sub

三.Gridview前面的编号,自动生成数据编号

GridView模板里面

                <asp:TemplateField HeaderText="No.">
                   
<ItemTemplate>
                   
<%#gdvShow2.PageIndex * gdvShow2.PageSize + gdvShow2.Rows.Count + 1%>
                   
</ItemTemplate>
                
</asp:TemplateField>

四.保存gridview换页的所有的数据到EXCEL

'可以保存gridview换页的所有的数据到EXCEL
 Protected Sub btnSaveToExcel_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles btnSaveToExcel.Click
        Response.AppendHeader(
"Content-Disposition""attachment; filename=ABOWEB.xls")
        Response.ContentType 
= "application/vnd.ms-excel"
        Response.ContentEncoding 
= System.Text.Encoding.UTF8
        
Me.EnableViewState = False
        
Dim sw As New System.IO.StringWriter
        
Dim hw As New System.Web.UI.HtmlTextWriter(sw)
        gdvPO.AllowPaging 
= False

        DatabindPO()
        
        
'div1.RenderControl(hw)
        gdvPO.RenderControl(hw)

        Response.Write(sw.ToString())
        Response.End()
        gdvPO.AllowPaging 
= True
        DatabindPO()
    
End Sub

  
    
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
        
'必須有此方法,否則RenderControl()方法會出錯 
    End Sub

 五.添加Gridview标题

‘可以添加Gridview标题
Protected Sub gdvPO_RowCreated(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvPO.RowCreated     
        
If e.Row.RowType = DataControlRowType.Header Then
            
Dim ogridview As GridView = CType(sender, GridView)
            
Dim ogirdviewrow As GridViewRow = New GridViewRow(00, DataControlRowType.Header, DataControlRowState.Insert)
            
Dim otablecell As TableCell = New TableCell
            
'COMPAL WEEKLY PO REPORT
            ogirdviewrow.BackColor = Drawing.Color.DarkOrchid
            ogirdviewrow.Font.Size 
= 20
            ogirdviewrow.HorizontalAlign 
= HorizontalAlign.Center
            otablecell.Text 
= "COMPAL WEEKLY PO REPORT "     ’Gridview标题

            otablecell.ColumnSpan 
= 11
            ogirdviewrow.Cells.Add(otablecell)
            ogridview.Controls(
0).Controls.AddAt(0, ogirdviewrow)
        
End If
    
End Sub

六.点击GridView模板里面的linkButton,传值给打开的页面。

'GridView 模板数据绑定
<ItemTemplate>  
  
<asp:Label ID="lblTAuthor" runat="server" text='<%#DataBinder.Eval(Container.DataItem,"Tauthor") %>'></asp:Label><br />
 
</ItemTemplate>
'GridView 模板数据绑定,点击数据可以传值
<asp:TemplateField HeaderText="论坛">                            
  
<ItemTemplate>                              
   
<asp:LinkButton ID="lkbTitle" CssClass="bgBoldLinks"  runat="server"  text='<%# DataBinder.Eval(Container.DataItem,"Board_Title") %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem,"id") %>' OnCommand="lkbTitle_Command" ></asp:LinkButton><br />                  
 
</ItemTemplate>

linkButton

 

Protected Sub lkbTitle_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
        Dim ID As String
        ID 
= CType(e.CommandArgument, String)
        Response.Redirect(
"TitleList.aspx?id=" + ID)
End Sub

七.GridView实现用“...”代替超长字符串

'GridView实现用“”代替超长字符串
 Private Sub BindIssueFile()
        Dim conn As SqlConnection 
= New SqlConnection(strConn)
        conn.Open()
        Dim strSql As String
        
'ikeli
        'Dim strNtAccount As String = User.Identity.Name
        'Dim strEngName As String = strNtAccount.Substring(strNtAccount.IndexOf("/") + 1).ToUpper
        Dim strEngName As String = "ike_li1"
        strSql 
= "select *from newIssue a,Issueflow b where a.issuetype=b.issuetype and a.CurrentSection=B.IssueRoad and b.ApproveEngname='" & strEngName.ToUpper & ""
        Dim ds As DataSet 
= New DataSet
        Dim da As SqlDataAdapter 
= New SqlDataAdapter(strSql, conn)
        da.Fill(ds, 
"file")
        gdvApproveWill.DataSource 
= ds
        gdvApproveWill.DataBind()
        Dim i As Integer
        For i 
= 0 To gdvApproveWill.Rows.Count - 1
            Dim mydrv As DataRowView
            Dim strCell As String
            If gdvApproveWill.PageIndex 
= 0 Then
                mydrv 
= ds.Tables("file").DefaultView(i)
                strCell 
= Convert.ToString(mydrv("IssueContent"))
                gdvApproveWill.Rows(i).Cells(
5).Text = SubStr(strCell, 6)
            Else
                mydrv 
= ds.Tables("file").DefaultView(i + (5 * gdvApproveWill.PageIndex))
                strCell 
= Convert.ToString(mydrv("IssueContent"))
                gdvApproveWill.Rows(i).Cells(
5).Text = SubStr(strCell, 6)
            End If
        Next i
        conn.Close()
    End Sub

Code
    Public Function SubStr(ByVal sString As String, ByVal nLeng As Integer) As String
        If sString.Length 
<= nLeng Then
            Return sString
        Else
            Dim sNewStr As String
            sNewStr 
= sString.Substring(0, nLeng)
            sNewStr 
= sNewStr + ""
            Return sNewStr
        End If
    End Function

八.页脚显示统计

'在页脚显示统计数
  Protected Sub gdvPUR_RowDataBound(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvPUR.RowDataBound
        
Static sum
        
If e.Row.RowIndex >= 0 Then
            sum 
= sum + CType(e.Row.Cells(1).Text, Integer)
        
Else
            
If e.Row.RowType = DataControlRowType.Footer Then
                e.Row.Cells(
0).Text = "Total Scrap:"
                e.Row.Cells(
1).Text = sum.ToString
            
End If
        
End If
    
End Sub

九.GridView 无记录是显示标题和提示

 

'GridView 无记录是显示标题和提示
'
vb
        If ds.Tables(0).Rows.Count > 0 Then
            gdvPE.DataSource 
= ds
            gdvPE.DataBind()
        
Else
            BindNORecords(gdvPE,ds)
        
End If

 
Public Sub BindNORecords(ByVal GridView As GridView, ByVal ds As DataSet)
        
If ds.Tables(0).Rows.Count = 0 Then
            ds.Tables(
0).Rows.Add(ds.Tables(0).NewRow())
            GridView.DataSource 
= ds
            GridView.DataBind()
            
Dim colCount As Integer = GridView.Rows(0).Cells.Count
            GridView.Rows(
0).Cells.Clear()
            GridView.Rows(
0).Cells.Add(New TableCell())
            GridView.Rows(
0).Cells(0).ColumnSpan = colCount
            GridView.Rows(
0).Cells(0).Text = "No Records Found."
            GridView.RowStyle.HorizontalAlign 
= System.Web.UI.WebControls.HorizontalAlign.Center
        
Else
        
End If
    
End Sub

C#

public void BindNoRecords(GridView gridView, DataSet ds)
{
     
if (ds.Tables[0].Rows.Count == 0)
     {
          ds.Tables[
0].Rows.Add(ds.Tables[0].NewRow());
          gridView.DataSource 
= ds;
          gridView.DataBind();
         
int columnCount = gridView.Rows[0].Cells.Count;
          gridView.Rows[
0].Cells.Clear();
          gridView.Rows[
0].Cells.Add(new TableCell());
          gridView.Rows[
0].Cells[0].ColumnSpan = columnCount;
          gridView.Rows[
0].Cells[0].Text = "没有数据";
          gridView.RowStyle.HorizontalAlign 
= System.Web.UI.WebControls.HorizontalAlign.Center;
     }
}

十.GridView嵌套GridView

html里面的代码

 

Code

 

Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Load
        
Dim conn As SqlConnection = New SqlConnection(strConn)
        conn.Open()
        
Dim sql As String = "select *from sno"
        
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
        
Dim ds As DataSet = New DataSet
        da.Fill(ds)
        conn.Close()
        GridView1.DataSource 
= ds
        GridView1.DataBind()
    
End Sub


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
            
Dim Grd As GridView = CType(e.Row.FindControl("Gridview2"), GridView)
            
If e.Row.RowIndex > 0 Then
                
If Not (Grd Is NothingThen
                    
Dim conn As SqlConnection = New SqlConnection(strConn)
                    conn.Open()
                  
Dim sql As String = "Select *from Attachment where sno=" + GridView1.DataKeys(e.Row.RowIndex).Value
                    
Dim da As SqlDataAdapter = New SqlDataAdapter(Sql, conn)
                    
Dim ds As DataSet = New DataSet
                    da.Fill(ds)
                    conn.Close()
                    Grd.DataSource 
= ds
                    Grd.DataBind()
                
End If
            
End If
        
End If
    
End Sub

 

 十一。操作GridView中的行

//获取GridView选中行的索引值 

string Ywbm = GridView1.DataKeys[e.RowIndex].Values[0].ToString();

//获取GridView模板列中的控件

string Ywmc = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtYwmc")).Text;

string Cdlb = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlCdlb")).SelectedValue.ToString();

//获取GridView页脚中的控件

string Ywbm = ((TextBox)GridView1.FooterRow.FindControl("txtAddYwbm")).Text;

//获取GridView选中行中的控件        

string cdbm = Server.HtmlDecode(GridView1.Rows[e.RowIndex].Cells[0].Text);

string cdmc = Server.HtmlDecode(GridView1.Rows[e.RowIndex].Cells[1].Text);

string sjbm = Server.HtmlDecode(GridView1.Rows[e.RowIndex].Cells[2].Text);

//string cdbm = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值