联合主键的情况怎么在DataGrid中利用DataKeys定位记录

比如表中三个字段
key1 int,key2 int,item varchar(50)
前面2个字段联合主键

前台代码:

< asp:DataGrid  id ="DataGrid1"  runat ="server"  AutoGenerateColumns ="False"  DataKeyField ="DoubleKey" >
                
< Columns >
                    
< asp:BoundColumn  DataField ="item"  HeaderText ="item" > asp:BoundColumn >
                    
< asp:ButtonColumn  CommandName ="del"  Text ="删除" > asp:ButtonColumn >
                
Columns >
            
asp:DataGrid >


后台代码:

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Data.SqlClient;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;

namespace  csdn2
{
    
public class WebForm20 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(!IsPostBack)
            
{
                SetBind();
            }

        }

        
private void SetBind()
        
{
            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            SqlDataAdapter da
=new SqlDataAdapter("select * from doublekey",conn);
            DataSet ds
=new DataSet();
            da.Fill(ds);
            DataTable dt
=ds.Tables[0];
            DataColumn dc
=new DataColumn("DoubleKey",typeof(string),"key1+'#'+key2");
            dt.Columns.Add(dc);
            
this.DataGrid1.DataSource=dt;
            
this.DataGrid1.DataBind();
        }

        
Web 窗体设计器生成的代码

        
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        
{
            
if(e.CommandName=="del")
            
{
                SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]); 
                SqlCommand comm
=new SqlCommand("delete from doublekey where key1=@key1 and key2=@key2",conn); 
                SqlParameter parm1
=new SqlParameter("@key1",SqlDbType.Int);
                SqlParameter parm2
=new SqlParameter("@key2",SqlDbType.Int); 
                
string [] keys=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString().Split('#');
                parm1.Value
=keys[0];
                parm2.Value
=keys[1];
                comm.Parameters.Add(parm1);
                comm.Parameters.Add(parm2); 
                conn.Open(); 
                comm.ExecuteNonQuery(); 
                conn.Close(); 
                SetBind(); 
            }

        }

    }

}

 

你可能感兴趣的:(DataGrid控件使用技巧)