Error with the event handlers of dynamic linkbutton - asp.net

I am retrieving data from database depending upon the texboxes input and storing in a datatable , after then from datatable im sending data into dynamic table and displaying table in a panel,in the table all the data of the first column are of linkbuttons, i wrote event handler for dynamic link buttons , but the event handler is not triggering, and i want to store the linkbutton text in a string in the event handler, but the event handler is not triggering.
Code:
protected void Button1_Click(object sender, EventArgs e)
{
// GridView1.
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(str);
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select ID,title,desc from [SO] where ID='" + TextBox1.Text.ToString() + "'or title='" + TextBox2.Text.ToString() + "'";
OleDbDataAdapter db = new OleDbDataAdapter(cmd);
db.Fill(dt);
Table tb = new Table();
tb.BorderColor = Color.Black;
tb.BorderWidth = 2;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
TableRow tr = new TableRow();
tr.BorderColor = Color.Black;
tr.BorderWidth = 2;
tr.ID = "tr" + i;
TableCell tc = new TableCell();
tc.BorderColor = Color.Black;
tc.BorderWidth = 2;
tc.ID = "tc" + i;
TableCell tc1 = new TableCell();
tc1.BorderColor = Color.Black;
tc1.BorderWidth = 2;
tc1.ID = "tc1" + i;
TableCell tc2 = new TableCell();
tc2.BorderColor = Color.Black;
tc2.BorderWidth = 2;
tc2.ID = "tc2" + i;
LinkButton t = new LinkButton();
t.BorderColor = Color.Black;
t.BorderWidth = 2;
t.ID = "t" + i;
t.Click += new EventHandler(t_edit);
TextBox t1 = new TextBox();
t1.BorderColor = Color.Black;
t1.BorderWidth = 2;
t1.ID = "t1" + i;
TextBox t2 = new TextBox();
t2.BorderColor = Color.Black;
t2.BorderWidth = 2;
t2.ID = "t2" + i;
dr = dt.Rows[i];
t.Text = Convert.ToString(dr["ID"]);
t1.Text = Convert.ToString(dr["title"]);
t2.Text = Convert.ToString(dr["desc"]);
tc.Controls.Add(t);
tc1.Controls.Add(t1);
tc2.Controls.Add(t2);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tb.Rows.Add(tr);
}
Panel1.Controls.Add(tb);
}
protected void t_edit(object sender, EventArgs e)
{
}
k but by using the sessions concept im retrieving the total table so that the linkbuttons are also retrieving , and i want to add the linkbttons on a button click , here the problem is the eventhandler is not assiging to the linkbutton, and im adding linkbuttons on button click,not on page load.

You must have to use Page_Init or Page_Load event handler to write code that create controls dynamically. Please read MSDN pages on How to add controls dynamically and ASP.NET Page life cycle articles.

You can add event handlers to the Page_Load event but the important think to remember is that they must be added on every page load. It is common to do setup type tasks such as this in a !Page.IsPostBack clause. When wiring up event handlers that's not the case otherwise they will seem to disappear
if(!Page.PostBack)
{
control.EventRaised += new EventHandler(EventResponse)
}
is wrong and will result in the handler disappearing on postback

Related

how to find control of static control without for loop

private void searchgrid()
{
GridViewRow HeaderGridRow = new GridViewRow(0, 1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "";
TextBox abc = new TextBox();
HeaderCell.Controls.Add(abc);
HeaderCell.ColumnSpan = 3;
HeaderGridRow.Cells.Add(HeaderCell);
HeaderCell = new TableCell();
HeaderCell.Text = "";
TextBox search = new TextBox();
search.ID = "search1";
HeaderCell.Controls.Add(search);
HeaderCell.ColumnSpan = 3;
HeaderGridRow.Cells.Add(HeaderCell);
HeaderCell = new TableCell();
Button btn_chk = new Button();
btn_chk.Text = "go";
HeaderCell.Controls.Add(btn_chk);
HeaderCell.ColumnSpan = 1;
btn_chk.Click += new EventHandler(btnClick);
HeaderGridRow.Cells.Add(HeaderCell);
//tbl1.Controls.Add(HeaderGridRow);
//btn_chk.CommandName = "btn_chk";
GridView2.Controls[0].Controls.AddAt(0, HeaderGridRow);
//GridView2.Controls[0].Controls.AddAt(0, tbl1);
}
i have a gridview,inside this there is another dynamically created gridview which hAS a textbox.how to find control of this textbox.by looping i get the values but i don get the desired output..so i need just one textbox value..please help
You can do it without a loop like this:
GridView gv = GridView1.Rows[0].FindControl("GridView2") as GridView;
TextBox tb = gv.Rows[0].FindControl("TextBox1") as TextBox;
string tbValue = tb.Text;
You find the nested GridView first and cast it, then you can find the TextBox in the nested GridView.
And you could still always use a loop:
foreach (GridViewRow parentRow in GridView1.Rows)
{
if (parentRow.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)parentRow.FindControl("GridView2");
foreach (GridViewRow childRow in gv.Rows)
{
if (childRow.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)childRow.FindControl("TextBox1");
string tbValue = tb.Text;
}
}
}
}

Populate Table with Table Rows and Cells on LinkButton click event while getting info from XML

Basically I create Rows then Cells then i populate the Cells with LinkButton which is getting Text value from XML nodes .
Code :
private void linkBTN_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
string text = btn.Text.ToString();
XmlDocument clickDoc = new XmlDocument();
clickDoc.Load(Server.MapPath("~/ProductShow.xml"));
XmlNodeList btnNode = clickDoc.SelectNodes("products/" + text.ToString() + "/*");
int count = btnNode.Count;
foreach (XmlNode node in btnNode)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.CssClass = "Cell";
LinkButton linkbtn = new LinkButton();
linkbtn.Text = node.InnerText;
linkbtn.Attributes.Add("runat", "server");
Image img = new Image();
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl("<br/>"));
cell.Controls.Add(img);
row.Cells.Add(cell);
MainTable.Rows.Add(row);
}
}
My problem is that i want to create 4 cells for each row and my code creates 1 cell for each row untill the Nodes end
You need another loop to add more columns to each row
foreach (XmlNode node in btnNode)
{
TableRow row = new TableRow();
for (int i = 0; i < 4; i++){
TableCell cell = new TableCell();
cell.CssClass = "Cell";
LinkButton linkbtn = new LinkButton();
linkbtn.Text = node.InnerText;
linkbtn.Attributes.Add("runat", "server");
Image img = new Image();
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl("<br/>"));
cell.Controls.Add(img);
row.Cells.Add(cell);
}
MainTable.Rows.Add(row);
}

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Bind a multi-dimensional ArrayList to a Gridview

I have a DataGrid of seats available, each with a checkbox to be able to reserve the seat. In the button click event, if the CheckBox is clicked, I am adding the contents of the row to an ArrayList, then adding the ArrayList to a session before redirecting to the confirmation page:
protected void Reserve_Click(object sender, EventArgs e)
{
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
string tempRowInfo = lblSection.Text + "|" + lblRow.Text + "|" + lblPrice.Text;
seatingArreaList.Add(tempRowInfo);
}
}
// Add the selected seats to a session
Session["Seating"] = seatingArreaList;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
On the confirmation page, Id like to split this array up and bind it to another gridview in their individual columns.
On the confirmation page, a session exists that has three columns separated with a pipe, I am struggling to split this up and bind it to a confirmation grid.
Please help!
This would probably be easier to just create a DataTable, then add it to the session variable. Once redirected to the confirmation page just bind GridView to the DataTable pulled from the session variable.
protected void Reserve_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Section");
dt.Columns.Add("Row");
dt.Columns.Add("Price");
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
DataRow dr = dt.NewRow();
dr["Section"] = lblSection.Text;
dr["Row"] = lblRow.Text;
dr["Price"] = lblPrice.Text;
dt.Rows.Add(dr);
}
}
// Add the selected seats to a session
Session["Seating"] = dt;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
var q = from dto in seatingArreaList
let z = dto.Split("|".ToCharArray())
select z;
and then just bing q to the grid.

asp.net gridview template column

In my asp.net gridview, I am placing a template column which displays an image.
Inside the template column I added an image control, and it successfully displaying the images from the database. I am also using paging.
Paging also happening but when I do paging images are not coming in the gridview in proper order for example first three pages it diplays suppose a.jpg, b.jpg,c.jpg and when I click on page number it repeats the same picture instead of remaining pictures, i am using if(!ispostback) in the load event also. please help me out.
my code in page load event is:
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
path = Server.MapPath(#"~\images");
if (!IsPostBack)
{
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
}
and my code in paging event is
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
thank in advance
sangita
When you write your paging method you still need to re-query the datasource and rebind your gridview (along with setting the PageIndex).
assuming that you have only the image name stored in the database you can do this in the Image Control in you template column
set the databinding for the image url as
String.Format("images/{0}",Eval("photo"))
and as boon has said
When you write your paging method you
still need to re-query the datasource
and rebind your gridview (along with
setting the PageIndex).
you can declare a method that fetches the records from the database as
protected void fillData()
{
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and use it to bind data to your gridview
and in your paging_indexChanging function
GridView1.PageIndex = e.NewPageIndex;
fillData();
Please verify the image paths in pagination. If the images paths are same, then disable the browser cache.

Resources