Love in coding...

    Free and Susan

统计

积分与排名

techLINKS

我参与的团队

友情链接

最新评论

VS2005中GridView簡單應用

GridView是VS2005中對VS2003的DataGrid的增強替代控件
下面展示一下它的基本常見應用
效果圖如下:

[查詢]按鈕:查詢數據庫 ,顯示信息Table 並 綁定GridView
//查詢按鈕
protected void btnQue_Click(object sender, EventArgs e)
 {
this.tableInfo.Visible = true;
SqlConnection sqlconn = new SqlConnection("server=localhost;database=db;uid=uid;pwd=pwd;");
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from table", sqlconn);
DataSet ds = new DataSet();
sda.Fill(ds);
this.grvInfo.DataSource = ds;
this.grvInfo.DataBind();
sda.Dispose();
ds.Dispose();
sqlconn.Close(); 
}

[全選]按鈕:
  //全選
    protected void btnAllCh_Click(object sender, EventArgs e)
    {
        foreach(GridViewRow currow in grvInfo.Rows)
        {
            ((CheckBox)currow.Cells[0].Controls[1]).Checked = true;
        }
    }
類似的[取消全選]的編碼為:
    // 取消全選
    protected void btnNoCh_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow currow in grvInfo.Rows)
        {
            ((CheckBox)currow.Cells[0].Controls[1]).Checked = false;
        }
    }
[明細]按鈕:
該按鈕的操作,要寫在GridView ROW按鈕事件--- RowCommand
    // GridView ROW按鈕事件 RowCommand
    protected void grvInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       if(e.CommandName.Equals("mingxin"))
        {          
        ImageButton lb = (ImageButton)e.CommandSource;
        GridViewRow curgvr = (GridViewRow)lb.Parent.Parent;
        string paraValue = curgvr.Cells[2].Text.ToString();
        //RegisterClientScriptBlock("openmingxin", "<script language='javascript'>window.open(src='mingxin.aspx?pihao="+ paraValue+"','newwindow','');</script>");    
        ClientScript.RegisterClientScriptBlock(this.GetType(), "aa", "<script language='javascript'>alert("+paraValue +"');</script>");
        }
    }     
[刪除]按鈕:
可以在HTML原始檔中加上
<asp:BoundField HeaderText="審核" />
<asp:TemplateField HeaderText="刪除">
<ItemStyle  HorizontalAlign="Center" />                           
<ItemTemplate>
<asp:ImageButton runat="server" ImageUrl="~/image/del.JPG" ID="delid"  CommandName="del"  OnClientClick="return confirm('確實要刪除嗎?');" />
</ItemTemplate>
</asp:TemplateField>
同時也可以如[明細]按鈕在GridView ROW按鈕事件--- RowCommand 對[刪除]點擊按鈕的事件進行服務器端處理!
============================
GridView中 样板列 加入 按钮
============================
前台:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="personName" />
        <asp:BoundField DataField="personAge" />
        <asp:TemplateField HeaderText="操作">
        <ItemTemplate>
            <asp:Button ID="btn_OK" runat="server" Text="确定"
            CommandArgument='<%# Eval("personName") %>' CommandName="btn_OK" />
            <asp:Button ID="btn_Cancel" runat="server" Text="取消" CommandName="btn_Cancel"
            CommandArgument='<%# Eval("personName") %>' />
        </ItemTemplate>
       </asp:TemplateField>
    </Columns>
</asp:GridView>
后台:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //直接利用参数
    string strName = e.CommandArgument.ToString();
    //一种取得当前行的方法
    GridViewRow currRow = (GridViewRow)((Button)e.CommandSource).Parent.Parent;
    string strAge = currRow.Cells[1].Text.ToString();
    if (e.CommandName == "btn_OK")
    {
        this.TextBox1.Text = "确定按钮 " + strName + " " + strAge;
    }
    if (e.CommandName == "btn_Cancel")
    {
        this.TextBox1.Text = "取消按钮 " + strName + " " + strAge;
    }
}

 

============================
GridView的CommandField列的 编辑 更新 取消
============================
页面部分:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit" >
   <Columns>
       <asp:TemplateField>
            <HeaderTemplate>
                    姓名
            </HeaderTemplate>
            <EditItemTemplate>
                   <asp:TextBox runat="server" ID="txtName" Text='<%# Bind("colName") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                   <asp:Label runat="server" ID="lblName" Text='<%# Bind("colName") %>'></asp:Label>
             </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ButtonType="Button" ShowEditButton="True" />
   </Columns>
</asp:GridView>
后台部分:
需要对上面OnRowEditing/OnRowUpdating事件进行相关代码编写
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    this.GridView1.EditIndex = e.NewEditIndex;
    BindData();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //取得当前的编辑值 以便进行保存
    string strName = "";
    strName = ((TextBox)this.GridView1.Rows[e.RowIndex].FindControl("txtName")).Text.Trim();
    //相关保存...

    //重新绑定显示
    this.GridView1.EditIndex = -1;
    BindData();
}


 

posted on 2006-02-09 17:29 freeliver54 阅读(9310) 评论(20)  编辑 收藏 网摘 所属分类: VS技術實踐

评论

#1楼 [楼主] 2006-12-30 19:04 freeliver54      

#region gv_showResult 数据绑定时的事件
/// <summary>
/// gv_showResult 数据绑定时的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gv_showResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
//设定宽度
e.Row.Cells[0].Width = 240;
e.Row.Cells[1].Width = 340;

if (e.Row.RowIndex == -1)
return;
//加载鼠标单击事件
string strID = e.Row.Cells[0].Text.Trim();
string strName = e.Row.Cells[1].Text.Trim();
string strJS = "document.all.txt_ID.value='" + strID + "';";
strJS += "document.all.hidtxt_ID.value='" + strID + "';";
strJS += "var tmpName = escape('" + strName + "');";
strJS += "document.all.txt_Name.value=unescape(tmpName);";
//加载点击后 变色
strJS += "OnSelectBgColor(this,gv_showResult)";
e.Row.Attributes.Add("onclick", strJS);
e.Row.Attributes.Add("onmouseover", "mouseover(this);");
e.Row.Attributes.Add("onmouseout", "mouseout(this,gv_showResult);");

}
#endregion   回复  引用  查看    

#2楼 [楼主] 2007-01-17 08:45 freeliver54      

一般情况下GridView 隐藏列
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hidtxt_currID" runat="server" Text='<%# Bind("currID") %>' style="display:none"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
后台抓值
string strCurrID = ((TextBox)this.gv_Selected.Rows[i].Cells[0].FindControl("hidtxt_currID")).Text.Trim();   回复  引用  查看    

#3楼 [楼主] 2007-01-17 08:46 freeliver54      

ajax情况下GridView 隐藏列
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hidtxt_currID" runat="server" Text='<%# Bind("currID") %>' style="display:none"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
注意<HeaderTemplate>也需要display:none
后台抓值
string strCurrID = ((TextBox)this.gv_Selected.Rows[i].Cells[0].FindControl("hidtxt_currID")).Text.Trim();   回复  引用  查看    

#4楼 [楼主] 2007-01-29 11:49 freeliver54      

自定义数据绑定:
VS2003 DataGrid 的 ItemDataBound 事件:
e.Item.Cells[0].Text=((String)DataBinder.Eval(e.Item.DataItem, "Name"));
VS2005 GridView 的 RowDataBound 事件:
if (e.Row.RowIndex >= 0)
{
DropDownList tmpDrpSex = (DropDownList)e.Row.FindControl("drp_Sex");
tmpDrpSex.Items.Clear();
tmpDrpSex.Items.Add(new ListItem("女","0"));
tmpDrpSex.Items.Add(new ListItem("男","1"));
tmpDrpSex.SelectedValue = DataBinder.Eval(e.Row.DataItem, "ASex").ToString();
}   回复  引用  查看    

#5楼 [楼主] 2007-05-15 15:35 freeliver54      

//某个字段的内容太长时
//在GridView上的该字段上显示截断前多少字的内容
//当鼠标放上时 弹出小提示框 显示完整内容
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1)
return;
string strAllContent = ((TextBox)e.Row.Cells[0].FindControl("hidtxt_AllContent")).Text.Trim();
e.Row.Cells[5].Attributes.Add("title", strAllContent);
}
  回复  引用  查看    

#6楼 [楼主] 2007-05-28 17:59 freeliver54      

//鼠标经过时
//显手形
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand'");
e.Row.Attributes.Add("onmouseout", "this.style.cursor=''");   回复  引用  查看    

#7楼 [楼主] 2007-07-30 14:51 freeliver54      

<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="gvbtn_Edit"
CommandName="gv_btn_Edit" Text="查看" CommandArgument="<%# gv_DataShow.Rows.Count %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DataFieldA" HeaderText="DataFieldA" >
<ItemStyle CssClass="hidden" />
<HeaderStyle CssClass="hidden" />
</asp:BoundField>   回复  引用  查看    

#8楼 [楼主] 2007-08-17 14:23 freeliver54      

GridView 分页 排序
http://www.cnblogs.com/freeliver54/archive/2007/08/09/848953.html   回复  引用  查看    

#9楼 [楼主] 2007-10-11 09:40 freeliver54      

通过Grid表头的新增按钮 新增Grid一空白行 以便用户输入相关资料
每行的结尾的删除按钮 可以删除当前Grid行的相关资料并重新绑定Grid显示
http://www.cnblogs.com/freeliver54/archive/2007/10/10/919835.html   回复  引用  查看    

#10楼 [楼主] 2008-01-17 10:16 freeliver54      

GridView自动序号
第一种方式,直接在Aspx页面GridView模板列中.这种的缺点是到第二页分页时又重新开始了.
<asp:TemplateField HeaderText="序号" InsertVisible="False">
              <ItemStyle HorizontalAlign="Center" />
              <HeaderStyle HorizontalAlign="Center" Width="5%" />
             <ItemTemplate>
              <%#Container.DataItemIndex+1%>
            </ItemTemplate>
            </asp:TemplateField>
第二种方式分页时进行了计算,这样会累计向下加.
<asp:TemplateField HeaderText="序号" InsertVisible="False">
              <ItemStyle HorizontalAlign="Center" />
              <HeaderStyle HorizontalAlign="Center" Width="5%" />
             <ItemTemplate>
                 <asp:Label ID="Label2" runat="server" Text='<%# this.MyListGridView.PageIndex * this.MyListGridView.PageSize + this.MyListGridView.Rows.Count + 1%>'/>
            </ItemTemplate>
            </asp:TemplateField>
还有一种方式放在cs代码中,和第二种相似.
<asp:BoundField HeaderText="序号" >
              <ItemStyle HorizontalAlign="Center" />
              <HeaderStyle HorizontalAlign="Center" Width="5%" />
          </asp:BoundField>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex != -1)
            {
                int indexID = this.myGridView.PageIndex * this.myGridView.PageSize + e.Row.RowIndex + 1;
                e.Row.Cells[0].Text = indexID.ToString();
            }
        }
都是非常简单的,其实原理都是一样的.实现同一种效果,方法很多,实际上读取数据的时候也可以实现.
为了不至于字数太多,给阅读带来不便,SQL的方法放在以下链接里面:其实都是非常简单的入门级,可是有的时候容易忘记.

Sql Server中自动序号的方法
第一种:使用identity函数增加临时表的方法
select id = identity(int,1,1),* into #tmp from table
select * from #tmp
drop table #tmp

在SQL2005中新增了ROW_NUMBER()函数,给我们带来了很多方便,使用方法如下:
SELECT id,ROW_NUMBER() OVER (order by id)as RowNumber FROM Table有一个方便,as后的别名可以在语句后面作为条件单独使用.

  回复  引用  查看    

#11楼 [楼主] 2008-03-21 11:51 freeliver54      

GridView RadioButton 样板列
http://www.cnblogs.com/freeliver54/archive/2008/03/21/1116075.html   回复  引用  查看    

#12楼 [楼主] 2008-04-03 10:44 freeliver54      

//页面显示时 调用后台的相关方法
//页面部分
<asp:TemplateField HeaderText="核对与否">
<ItemTemplate>
<div>
<%# fn_IsCheckValue(Convert.ToString(Eval("IsChecked")))%>
</div>
</ItemTemplate>
</asp:TemplateField>
//后台部分
#region 根据核对与否的值 返回文本
public string fn_IsCheckValue(string strIsChecked)
{
if (strIsChecked == "")
return "未核对";
else if (strIsChecked == "0")
return "未核对";
else if (strIsChecked == "1")
return "核对通过";
else if (strIsChecked == "2")
return "核对未通过";
else
return "未核对";
}
#endregion   回复  引用  查看    

#13楼  2008-04-14 21:16 techmango [未注册用户]

感觉GridView比GridView好用多了!   回复  引用    

#14楼 [楼主] 2008-06-03 11:10 freeliver54      

GridView 的EmptyDataText 及 EmptyDataTemplate
http://www.cnblogs.com/freeliver54/archive/2008/06/03/1212692.html   回复  引用  查看    

#15楼 [楼主] 2008-06-16 14:47 freeliver54      

删除按钮的前台js的confrim语句 可扩充为如下:
OnClientClick='<%# DataBinder.Eval(Container.DataItem,"Name","return confirm(\"确定删除[{0}]吗?\");") %>'   回复  引用  查看    

#16楼 [楼主] 2008-06-16 14:51 freeliver54      

请教关于DataBinder.Eval帮定两个字段的用法,如下
<asp:HyperLink NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"VisID","../Article/ArticleCard.aspx?CardID={0}&Name={1}")%>' Runat=server ID="Hyperlink2">打开</asp:HyperLink>

我想在../Article/ArticleCard.aspx?CardID={0}&Name={1}中传入编号及名称两个参数,那上面那个要如何实现?

NavigateUrl='<%# "../Article/ArticleCard.aspx?CardID="+DataBinder.Eval(Container.DataItem,"VisID")+"&Name="+DataBinder.Eval(Container.DataItem,"Name"))%>'

楼上的,正确..其实你还可以在后台写个过程来实现

NavigateUrl='<%# getURL(DataBinder.Eval(Container.DataItem,"VisID"),DataBinder.Eval(Container.DataItem,"Name"))%>'

然后在后台处理:
function getURL(a as object,b as object) as string
return "<>.a.toString...</>"
end function

  回复  引用  查看    

#17楼 [楼主] 2008-06-16 15:12 freeliver54      

<%@ Import Namespace="System.Data" %>

<script type="text/javascript" language="javascript">

function fn_IsDelete(a,b)
{
alert("a");
alert(a);
alert(b);
return false;
}
</script>

OnClientClick='<%# "return fn_IsDelete("+DataBinder.Eval(Container.DataItem,"BuildingName")+","+DataBinder.Eval(Container.DataItem,"BuildingName")+");" %>'   回复  引用  查看    

#18楼 [楼主] 2008-06-19 14:50 freeliver54      

OnClientClick='<%# "return confirm(\"确定删除该[ OX " + int.Parse(Eval("PID").ToString()).ToString("x") + " ]的相关信息吗?\");" %>'   回复  引用  查看    

#19楼  2008-08-06 16:10 freea [未注册用户]

RowDataBound时得到所绑定数据源中的某个字段
string strUserName = DataBinder.Eval(e.Row.DataItem, "UserName").ToString();   回复  引用    

#20楼  2008-09-22 09:16 free54 [未注册用户]

在html页面的GridView的模版列上使用包含汉字的链接
http://www.cnblogs.com/freeliver54/archive/2008/09/22/1223865.html#1323185   回复  引用    





标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-11-18 08:26 编辑过
Google站内搜索

China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!
开发者征途系统新作:《设计模式——基于C#的工程化实现及扩展》

相关文章:

相关链接: