GridView使用DataKeyNames的例子 & CommandArgument传递多个参数 & 获取GridView编辑状态下单元格里的值

   在asp.net2.0中,当我们需要在GridView的ItemDataBound之类的事件中需要获取当前行的一些关联性的数据值,但这些数据值又 不能直接体现在GridView的列中显示出来,这时我们可以采用DataKeyNames的方式来获取此类数据,看下面的代码示例:

前台代码:
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Grup" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("GrupName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:ButtonField Text="按钮" />
            </Columns>
        </asp:GridView>
其中:Grup为我们想使用但不需要显示的列。(如果有多个字段,使用逗号分开)

后台代码:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack )
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Grup");
            dt.Columns.Add("GrupName");

            dt.Rows.Add(new object[] { 0,"营业部" });
            dt.Rows.Add(new object[] { 1,"市场部" });

            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // 获取当前行索引
        int index = Convert.ToInt32(e.CommandArgument);

        // 取出当前行数据键值对象中的值
        string strGrup = ((GridView)sender).DataKeys[index].Values["Grup"].ToString()
    }

顺便补充一句。
如果你使用模板列中放置按钮控件的方式,要想在按钮事件中获取这种字段值就更简单了。

只需要在按钮的CommandArgument属性设置为想绑定的字段,如:

<asp:TemplateField>
     <ItemTemplate>
         <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" CommandArgument=' <%#Eval("Grup") %>' />
     </ItemTemplate>
</asp:TemplateField>

按钮事件中如是写:

protected void Button2_Click(object sender, EventArgs e)
{
    string strGrup = ((Button)sender).CommandArgument.ToString();
}

 


GridView控件给CommandArgument传递多个参数示例

 

 

GridView控件给CommandArgument传递多个参数示例,具体示例如下:

GridView使用DataKeyNames的例子 & CommandArgument传递多个参数 & 获取GridView编辑状态下单元格里的值 html代码
< asp:GridView  ID ="GVSecondType"  runat ="server"  AutoGenerateColumns ="False"  Style ="position: relative"  Width ="100%"  CellPadding ="4"  BackColor ="White"  BorderColor ="#3366CC"  BorderStyle ="None"  BorderWidth ="1px"  AllowPaging ="True"  OnPageIndexChanging ="GVSecondType_PageIndexChanging"  OnRowCommand ="GVSecondType_RowCommand" >
        
< Columns >
            
< asp:TemplateField  HeaderText ="所属一级分类" >
                
< EditItemTemplate >
                    
< asp:TextBox  ID ="TextBox3"  runat ="server" ></ asp:TextBox >
                
</ EditItemTemplate >
                
< ItemTemplate >
                    
< asp:Label  ID ="lblName"  runat ="server"  Style ="position: relative"  Text ='<%#Eval("Parent_TypeName1")  % > '> </ asp:Label >
                
</ ItemTemplate >
            
</ asp:TemplateField >
            
< asp:BoundField  DataField ="Id"  HeaderText ="分类ID"   />
            
< asp:BoundField  DataField ="Type_Name"  HeaderText ="分类名"   />
             
< asp:BoundField  DataField ="Parent_Id"  HeaderText ="所属父类"   />
            
< asp:BoundField  DataField ="Type_AddTime"  HeaderText ="添加时间"   />
            
< asp:TemplateField  HeaderText ="编 辑" >
                
< EditItemTemplate >
                    
< asp:TextBox  ID ="TextBox1"  runat ="server" ></ asp:TextBox >
                
</ EditItemTemplate >
                
< ItemTemplate >
                   
< div  style ="width:70px;line-height:20px; cursor:pointer;background-color:#CCCCCC; border:solid 1px #000000; " >< a   style ="text-decoration:none; cursor:pointer"  href ='ModifySecondType.aspx?TypeId=<%#Eval("Id")  % > '>修改 </ a ></ div >
                
</ ItemTemplate >
            
</ asp:TemplateField >
            
< asp:TemplateField  HeaderText ="删 除" >
                
< EditItemTemplate >
                    
< asp:TextBox  ID ="TextBox2"  runat ="server" ></ asp:TextBox >
                
</ EditItemTemplate >
                
< ItemTemplate >
                    
< div  onmouseover ="javascript:this.style.cursor='hand'"  style ="width:70px; line-height:20px;background-color:#CCCCCC;border:solid 1px #000000;" >   < asp:LinkButton  ID ="LinkButton1"  CommandName ="del"  CommandArgument ='<%#  Eval("Parent_Id")+","+Eval("Id")  % > '  runat="server">删除 </ asp:LinkButton ></ div >
                
</ ItemTemplate >
            
</ asp:TemplateField >
          
        
</ Columns >
        
< FooterStyle  BackColor ="#99CCCC"  ForeColor ="#003399"   />
        
< RowStyle  BackColor ="White"  ForeColor ="#003399"   />
        
< SelectedRowStyle  BackColor ="#009999"  Font-Bold ="True"  ForeColor ="#CCFF99"   />
        
< PagerStyle  BackColor ="#99CCCC"  ForeColor ="#003399"  HorizontalAlign ="Left"   />
        
< HeaderStyle  BackColor ="#003399"  Font-Bold ="True"  ForeColor ="#CCCCFF"   />
    
</ asp:GridView >  


GridView使用DataKeyNames的例子 & CommandArgument传递多个参数 & 获取GridView编辑状态下单元格里的值 c#代码
protected   void  GVSecondType_RowCommand( object  sender, GridViewCommandEventArgs e)
    {
        
string  cmdName  =  e.CommandName;
        
if  (cmdName  ==   " del " )
        {
            
string [] estr  =  e.CommandArgument.ToString().Split( ' , ' );

            
int  Parent_Id  =  Convert.ToInt32(estr[ 0 ]);
            
int  TypeId  =  Convert.ToInt32(estr[ 1 ]);
            
bool  flag  =  YHTBLL.Second_TypeManage.DelTypeById(Parent_Id, TypeId);
            
if  (flag)
            {
                
this .Literal1.Text  =   " 删 除 成 功 " ;
                bind();
            }

            
else
            {
                
this .Literal1.Text  =   " 删 除失 败 " ;
                bind();
            }        }    }

 

 


 

 

.net如何获取GridView编辑状态下单元格里的值?先看下面这段代码

var txtName = grid1.Rows[e.RowIndex].Cells[0].FindControl("txtName"as TextBox;
if (txtName != null)
{
    
// 读取值
    
//
}
其实这些工作(在单元格中查找控件,并尝试获取其中的值)已经被封装了。现在,只要调用 ExtractValuesFromCell 方法即可。
而该方法也被很多种列类型所支持:

DataControlField, BoundField, AutoGeneratedField, CheckBoxField, ImageField, TemplateField, DynamicField

你可以在 GridView 的 RowUpdating, RowDeleting 等事件中使用它。利用该方法,可以将值提取到所需的字典里去,然后再从字典中读取。这些字典包括:e.Keys, e.NewValues, e.OldValues 等。
一小段例子代码:

    // 更新
    protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        var row = grid1.Rows[e.RowIndex];
        // 提取 Id 字段的值
        grid1.Columns[0].ExtractValuesFromCell(
            e.Keys,
            row.Cells[0] as DataControlFieldCell,
            DataControlRowState.Edit,
            true /* include readonly */);

        // 提取 Name 字段的值
        grid1.Columns[1].ExtractValuesFromCell(
            e.NewValues,
            row.Cells[1] as DataControlFieldCell,
            DataControlRowState.Edit,
            true /* include readonly */);

        var id = int.Parse(e.Keys["id"].ToString());
        var name = (string) e.NewValues["name"];

        // 执行相关的数据库更新操作
        //
    }

这样,在大多数场合我们可以尽可能多的使用 BoundField,并且也能正确读取到其编辑时的值,省下自定义 TemplateField 的一堆代码了。

 

 

 

 

 

你可能感兴趣的:(GridView)