DataGrid中的按钮反选事件与NamingContainer(命名容器)-downmoon

- 中国WEB开发者网络 (http://www.webasp.net)
-- 技术教程 (http://www.webasp.net/article/)
--- DataGrid中的按钮反选事件与NamingContainer(命名容器)-downmoon (http://www.webasp.net/article/29/28086.htm)
-- 作者:未知
-- 发布日期: 2007-01-08

DataGrid中想实现这样的效果:
根据某一字段列的值动态改变按钮的文本,比如:
点击按钮列,自动更新某列原为0的值为1,并将按钮列的文本改为“置0”,
再按下,自动更新某列原为1的值为0,并将按钮列的文本改为“置1”,

最终通过NamingContainer,实现! 方法如下 :


<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
                
<Columns>
                    
<asp:BoundColumn DataField="HonoreeID" HeaderText="ID"></asp:BoundColumn>
                    
<asp:BoundColumn DataField="status" HeaderText="状态">
                        
<HeaderStyle Width="300px"></HeaderStyle>
                    
</asp:BoundColumn>
                    
<asp:TemplateColumn HeaderText="状态是否为0">
                        
<HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>
                        
<ItemStyle HorizontalAlign="Center"></ItemStyle>
                        
<ItemTemplate>
                            
<asp:Label id="lb" runat="server" Visible="false" Text='<%# ((DataBinder.Eval(Container, "DataItem.status", "{0}"))=="0")?"是":"<font color=red></font>" %>'>
                            
</asp:Label>
                            
<asp:Button ID="changeState" Runat="server" Text='<%# ((DataBinder.Eval(Container, "DataItem.status", "{0}"))=="0")?"转为1":"转为0" %>'>
                            
</asp:Button>
                        
</ItemTemplate>
                    
</asp:TemplateColumn>
                
</Columns>
            
</asp:DataGrid>


后台:

protected System.Web.UI.WebControls.DataGrid DataGrid1;
   
        
public int  KeyID 
        
{
            
get
            
{
                
object o =ViewState ["KeyID"];
                
if(o!=null)
                
{
                    
return int.Parse(ViewState ["KeyID"].ToString());
                }

                
else
                
{
                    
return 0;
                }

            }

            
set
            
{
                ViewState [
"KeyID"]        = value;
            }

        }

        
public int  RowState 
        
{
            
get
            
{    return int.Parse(ViewState ["RowState"].ToString());
               
            }

            
set
            
{
                ViewState [
"RowState"]        = value;
            }

        }

        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(IsPostBack)
            
{return ;
            }

            getData();
        }



        
private void getData()
        
{
            
//SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DsnPubs"]);
   
            SqlConnection con 
= new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Mblog"]);
            SqlCommand  cmd;
            con.Open();
            cmd 
= new SqlCommand("select * from dbo.Honoree", con);
            DataGrid1.DataSource 
= cmd.ExecuteReader();
            DataGrid1.DataBind();
            con.Close();
        }


        
private bool UpdateData(int ID,int OldState)
        
{
            SqlConnection con 
= new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Mblog"]);
            SqlCommand  cmd;
            con.Open();
            
try
            
{
                
string strSql="Update Honoree set Status={0} where HonoreeID={1}";
                strSql
=string.Format(strSql,(OldState==0?1:0).ToString(),ID.ToString());
                cmd 
= new SqlCommand(strSql, con);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                
return true;
            }

            
catch
            
{
                
return  false;
            }

            
finally
            
{
                con.Close();
                con.Dispose();
               
            }

            
return  false;
        }



        
Web 窗体设计器生成的代码

        
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
if(e.Item.ItemType==ListItemType.Item  || e.Item.ItemType    ==    ListItemType.AlternatingItem)
            
{
                Button b
=(Button)e.Item.FindControl("changeState");
                
if(b!=null)
                
{
                   
                    b.Click
+=new EventHandler(b_Click);
                }

            }

       
        }


        
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
           
        }


        
private void b_Click(object sender, EventArgs e)
        
{
            Button but 
= (Button)sender;
            DataGrid dg 
= (DataGrid)but.NamingContainer.NamingContainer;
            
//此处是关键!!即找到包含按钮的命名容器的上层命名容器
            if(dg == nullreturn;
            DataGridItem di 
=(DataGridItem)but.NamingContainer;
            TableCell key
= (TableCell)di.Cells[0];
            TableCell state
= (TableCell)di.Cells[1];

            KeyID
=(key==null)?0:int.Parse(key.Text);
            RowState
=(state==null)?0:int.Parse(state.Text);
            Response.Write(UpdateData(
this.KeyID,this.RowState).ToString());
           
            getData();
        }

       


webasp.net