本文介绍了自定义控件中的GridView RowCommand事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我正在创建一个自定义控件.我在该控件中添加了一个GridView,如下所示.
Hello,
I am creating a custom control. I added a GridView in that control as below.
protected override void OnInit(EventArgs e)
{
SqlConnection con = new SqlConnection(connectionString);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new GridViewExtension(ListItemType.Header, "To Delete");
tf.ItemTemplate = new GridViewExtension(ListItemType.Item, "To Delete");
gvData.Columns.Add(tf);
gvData.RowCommand += new GridViewCommandEventHandler(gvData_RowCommand);
gvData.DataSource = ds;
gvData.DataBind();
gvData.Columns.Insert(0, tf);
}
protected override void RenderContents(HtmlTextWriter output)
{
gvData.RenderControl(output);
}
出现带有删除图像按钮的Gridview.
我需要编写代码以自行删除该控件中的行.我尝试使用RowCommand,但是它不起作用.是否有任何方法可以触发事件以删除记录?
Gridview is appearing with delete image button.
I need to write code for delete the row in that control it self. I tried with RowCommand but its not working.Is there any way to fire an event to delete the record?
推荐答案
// Generate Row Delete Event and then write following Code
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView YourGrid= sender as GridView;
}
protected void Page_Load(object sender, EventArgs e)
{
TemplateField tf = new TemplateField();
tf.ItemTemplate = new MyTemplateField();
GridView1.Columns.Add(tf);
GridView1.RowCommand += new GridViewCommandEventHandler(GridView1_RowCommand);
GridView1.DataSource = NewDataTable();
GridView1.DataBind();
}
模板字段
template field
public class MyTemplateField : Control, ITemplate
{
Button btn;
public MyTemplateField()
{
btn = new Button();
btn.ID = "this button";
btn.Text = "Im the button";
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
//GridView gridView = (sender as Button).NamingContainer as GridView ;
CommandEventArgs cea = new CommandEventArgs("cmd",btn);
//below line will bubble the event and gridview will capture it in RowCommand event handler
RaiseBubbleEvent(btn, cea);
}
public void InstantiateIn(Control container)
{
container.Controls.Add(btn);
}
}
您需要对事件进行冒泡.
希望它能工作.它对我有效;)
谢谢,
Hemant
you need to bubble the event.
Hope it will work. it worked at my end ;)
Thanks,
Hemant
这篇关于自定义控件中的GridView RowCommand事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!