GridView: cannot get data from dynamically created Textbox

J

JaM

Hi all,

I have created a gridview vith dynamic textbox columns (they are in
variable number, it depends on what things I select from database)

aspx code:
__________________________________________

<asp:GridView AutoGenerateColumns="false" ID="GridView2" Runat="server"<Columns>
</Columns>
</asp:GridView>

<ASP:BUTTON ID="buttSave" Runat="Server" CssClass="text" Text="Save"
onclick="buttSave_Click">
</ASP:BUTTON>
__________________________________________



this is the codebehind:
__________________________________________

protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack) //prima volta che entro nella pagina
{
GridView2.DataSource = MakeEditTable();
GridView2.DataBind();
}
}

private DataTable MakeEditTable()
{
//load data from db

DataTable dtab = new DataTable();
DataColumn dcol = new DataColumn();
BoundField bf = new BoundField();
TemplateField tf = new TemplateField();

dcol = new DataColumn();
dcol.DataType = typeof(int);
dcol.ColumnName = "Id";
dtab.Columns.Add(dcol);
bf = new BoundField();
bf.DataField = "Id";
bf.HeaderText = "Id";
GridView2.Columns.Add(bf);

dcol = new DataColumn();
dcol.DataType = typeof(string);
dcol.ColumnName = "Name";
dtab.Columns.Add(dcol);
tf = new TemplateField();
tf.ItemTemplate = new GridViewTemplate();
tf.HeaderText = "Name";
GridView2.Columns.Add(tf);

//cycle to add more columns with GridViewTemplate
}
__________________________________________



and this is the class GridViewTemplate:
(simplifyed for the 'Name' column only)
__________________________________________

public class GridViewTemplate : ITemplate
{
public GridViewTemplate()
{ }

void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
TextBox tb1 = new TextBox();
tb1.ID = "tbox_Name";
tb1.DataBinding += new EventHandler(tb1_DataBinding);
container.Controls.Add(tb1);
}

void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.GetPropertyValue(container.DataItem,
"Name");

if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
__________________________________________



When the page is loaded the GridView is populated with the correct
data, but when i click the button I cannot get the data from the
textbox.

I've tryed with

((TextBox)row.FindControl("tbox")).Text

and also with

((TextBox)GridView2.Rows.Cells[j].FindControl("tbox")).Text

but I always get a Null value...



Anyone can help me?
Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top