I am inheriting Gridview to add a functionality to add a record in the gridview. I bind the gridview with the sqldatasource. Assume that the category table has two fields "code" & "name"
Code:using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace GridUpControl { public class GridCustomControl : GridView, INamingContainer { public Button btn = new Button(); public TextBox txtbx = new TextBox(); public void ShowAddButton() { btn.Text = "Add"; btn.Click += new EventHandler(btn_Click); //Controls.Add(btn); } public void btn_Click(object sender,EventArgs e) { SqlConnection conn = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand(InsertText, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); this.DataBind(); } public GridCustomControl() : base() { } [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string InsertText { get { //EnsureChildControls(); String s = (String)ViewState["InsertText"]; return ((s == null) ? String.Empty : s); } set { //EnsureChildControls(); ViewState["InsertText"] = value; } } public string ConnectionString { get { //EnsureChildControls(); String s = (String)ViewState["ConnectionString"]; return ((s == null) ? String.Empty : s); } set { // EnsureChildControls(); ViewState["ConnectionString"] = value; } } protected override void Render(HtmlTextWriter writer) { base.Render(writer); btn.RenderControl(writer); } } }
Utilizing Code in default.aspx:
Now, the button click event is not fired. It remains ideal. Please help. I don't know the above code is optimum or not. Please help.Code:protected void Page_Load(object sender, EventArgs e) { GridCustomControl1.ShowFooter = true; GridCustomControl1.ConnectionString = ConfigurationManager.ConnectionStrings["TraineeDBConnectionString"].ConnectionString; TextBox CatName = (TextBox)GridCustomControl1.FooterRow.FindControl("CategoryNameTextBox"); GridCustomControl1.InsertText = "insert into ec_category(name) values('" + CatName.Text + "')"; GridCustomControl1.ShowAddButton(); }




Reply With Quote