Creating tables and displaying textboxes in codebehind - c#

I have a Dataset from the database which i want to display. My aim is to display a month's data on an aspx page using VS 2005 with 5 days per each row. I have written the code like this but i am confused with the i and j. This code displays nothing.
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
Table table = new Table();
table.ID = "Table1";
TableRow row = new TableRow();
TableCell cell = new TableCell();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
// I am not sure what i and j should be here to display 5 per each row..
for (int i = 0; i < 5; i++)
{
if (int j == 0; j < ds.Tables[0].Rows.Count; j ++)
{
tb1.ID = "txtDateRow" + x + "Col" + j;
tb1.Text = ds.Tables[0].Rows[x]["Date"].ToString();
tb2.ID = "txtDetails" + x + "Col" + j;
tb2.Text = ds.Tables[0].Rows[x]["AmountSold"].ToString();
cell.Controls.Add(tb1);
cell.Controls.Add(tb2);
table.Rows.Add(row);
}
}
Panel1.Controls.Add(table);
}
If someone could help me solve this, i really appreciate it. Thanks a lot.

row.Controls.Add(cell) is missing. Bcoz of this textbox controls are not added to the table and you are not able to see anything. Add this line and it will help you see. Later you can think about i & j.

You have a loop with a counter, namely, i but you test for j==0 what is j?
Is j initalized somewhere? Is j even declared? If not, are you sure you don't want to test for i == 0 ?
That is the reason you are not getting any results in the for loop.
The code:
tb1.ID = "txtDateRow" + x + "Col" + j;
tb1.Text = ds.Tables[0].Rows[x]["Date"].ToString();
tb2.ID = "txtDetails" + x + "Col" + j;
tb2.Text = ds.Tables[0].Rows[x]["AmountSold"].ToString();
cell.Controls.Add(tb1);
cell.Controls.Add(tb2);
table.Rows.Add(row);
Is inside a condition:
if (j == 0)
The question is does this condition ever happen? If so you need to post more code.
Debug your code and set breakpoints and watch how it runs. Per your edit you posted:
if (int j == 0; j < ds.Tables[0].Rows.Count; j ++)
This is not even valid, I think you need to pick up a book on C# syntax before you tackle this problem.

I'm not sure what 'x' is supposed to be in your code. I think the general structure should be something like this but the code below will add the same thing for each column:
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
Table table = new Table();
table.ID = "Table1";
// j is the row index
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
TableRow row = new TableRow();
// i is the column index
for (int i = 0; i < 5; i++)
{
TableCell cell = new TableCell();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
tb1.ID = "txtDateRow" + j + "Col" + i;
tb1.Text = ds.Tables[0].Rows[j]["Date"].ToString();
tb2.ID = "txtDetails" + j + "Col" + i;
tb2.Text = ds.Tables[0].Rows[j]["AmountSold"].ToString();
cell.Controls.Add(tb1);
cell.Controls.Add(tb2);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
Panel1.Controls.Add(table);
}

Related

Checking all the Checkboxes in a certain row by giving the row number in C#

I have Created Checkboxes like this:
but now i want to be able to check all the Checkboxes in one Row after giving the Row number
private void button4_Click(object sender, EventArgs e)
{
CheckBox[,] c = new CheckBox[10, 5];
for (i = 1; i < c.GetLength(0); i++)
{
for ( j = 1; j < c.GetLength(1); j++)
{
c[i, j] = new CheckBox();
c[i, j].Location = new Point(i * 50, j * 50);
c[i, j].AutoSize = true;
c[i, j].Name = i + "-" + j.ToString();
c[i, j].Text = i + "-" + j.ToString();
this.Controls.Add(c[i, j]);
}
}
You already use name:
for (i = 1; i < c.GetLength(0); i++)
{
for ( j = 1; j < c.GetLength(1); j++)
{
...
c[i, j].Name = i + "-" + j.ToString();
this.Controls.Add(c[i, j]);
}
}
So you could create a method to search against that:
private CheckBox Find(int row, int col)
{
foreach(var control in this.Controls)
{
if (control is CheckBox && control.Name == $"{row}-{col}")
return control as CheckBox;
}
}
So then just loop the rows and/or columns you want. This should check every even row:
for(var i = 1; i <= rowCount; i++)
{
if (i % 2 == 0)
{
for(var j = 1; i <= colCount; i++)
{
var checkBox = Find(i, j);
if (checkBox != null)
checkBox.Checked = true;
}
}
}
It's not the most efficient as each Find call is essentially looping over the controls so you'd be iterating multiple times but should work for a reasonable grid.
A shorter solution would use a jagged array instead, but with 2D array you can do the following:
You should change your check box array initialisation to this:
for (int i = 0; i < c.GetLength(0); i++)
{
for (int j = 0; j < c.GetLength(1); j++)
{
c[i, j] = new CheckBox
{
Location = new Point(i * 50, j * 50),
AutoSize = true,
Name = i + "-" + j.ToString(),
Text = i + "-" + j.ToString()
};
Controls.Add(c[i, j]);
}
}
If you still want their location to not be the upper left corner you can add 1 to the index like this:
Location = new Point((i + 1) * 50, (j + 1) * 50)
Than you can later obtain a row like this:
private CheckBox[] GetCheckBoxsByRow(int row, CheckBox[,] checkboxs)
{
CheckBox[] selectedRowCheckboxs = new CheckBox[checkboxs.GetLength(0)];
for (int x = 0; x < checkboxs.GetLength(0); x++)
{
selectedRowCheckboxs[x] = checkboxs[x, row - 1];
}
return selectedRowCheckboxs;
}
Example usage:
var firstRow = GetCheckBoxsByRow(1, c);

Dynamic button not firing click event or page life cycle for button(not dynamic)

I've got different entity types and depending on which entity is clicked (dropdownlist) the amount and types of uploads which is needed is different every time.
Thus, I am creating multiple dynamic upload controls in a dynamic table with a dynamic upload button to upload all files at the same time (I also tried adding a button on the asp.net page as well). Everything creates fine and I can choose the files to upload.
The problem that I am having is that the dynamic button control is not firing its onclicked event, thus I am not able to save the files. I tried creating a button on the asp.net side which does fire, but because of the page life cycle it's not picking up my upload controls.
I then tried to add the OnInit event and created the dynamic button in there and the rest of the upload dynamic controls on the selected index change of the dropdown, but then the everything gets created except the dynamic upload controls. The click event then fires. (the Page_Init does the same).
Preferably I would like the button not to be dynamic but reach the file upload controls to save the files. Is there a way around the page life cycle that I can achieve this or could anybody please tell me what I am doing wrong? Or how can I get the dynamic button to fire the click event?
Any help will be greatly appreciated....
Here is my code of what I done:
protected void lstLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
{
if (CTflag == false)
{
this.Rows = tblRow;
this.Columns = tblCol;
lblAmountOfRows.Text = "4";
CreateDynamicTable();
}
else
{
CTflag = true;
}
clrControls();
}
protected void CreateDynamicTable()
{
string filterstring = "";
filterstring = "SELECT let.ID, UploadType " +
"FROM [dbo].[AssetContract_LegalEntityLinks] lel " +
"INNER Join [dbo].[AssetContract_LegalEntity] le " +
"ON lel.LegalEntityRef = le.ID " +
"INNER JOIN [dbo].[AssetContract_LegalEntityTypes] let " +
"ON lel.LegalTypeRef = let.ID " +
"WHERE lel.LegalEntityRef = #LegalEntityRef ";
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = filterstring;
myCmd.Connection = cn;
myCmd.CommandType = CommandType.Text;
if (lstLegalEntity.SelectedValue != "")
{
myCmd.Parameters.AddWithValue("#LegalEntityRef", Convert.ToInt32(lstLegalEntity.SelectedValue));
}
else
{
myCmd.Parameters.AddWithValue("#LegalEntityRef", Convert.ToInt32(0));
}
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
tblRow = GetUploadControlsCount();
if (CTflag == false)
{
table.Caption = "Upload Requirements";
table.ID = "Upload Requirements";
table.BackColor = System.Drawing.Color.BurlyWood;
divFileUploads.Controls.Add(table);
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= tblCol; j++)
{
string[] Header = { "Upload Type", "File" };
Label lbl = new Label();
lbl.ID = "lblHeader" + j;
if (j == 1)
{
lbl.Width = 220;
}
else
{
lbl.Width = 100;
}
lbl.Text = Header[j];
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
int readCount = 1;
while (myReader.Read())
{
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.ID = "rw" + myReader["UploadType"].ToString();
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.ID = tbColId + i + j + myReader["UploadType"].ToString(); ;
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= 0; j++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + i + "Col" + j + myReader["UploadType"].ToString();
lbl.Text = myReader["UploadType"].ToString();
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 0; j < 1; j++)
{
fileUp = new FileUpload();
//m = i; n = j;
fileUp.ID = filename + i + readCount.ToString();
fileUp.Width = 350;
cell.Controls.Add(fileUp);
cmdArg = fileUp.ID;
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
readCount++;
}
i = 0;
j = 0;
}
for (i = 0; i < 1; i++)
{
rrow = new TableRow();
rrow.ID = "ResultRow";
rrow.BorderStyle = BorderStyle.Ridge;
rrow.HorizontalAlign = HorizontalAlign.Center;
for (j = 0; j <= tblCol; j++)
{
rcell = new TableCell();
rcell.ID = "resultCol" + j;
rcell.BorderWidth = 5;
rcell.BorderStyle = BorderStyle.Ridge;
rcell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j < 1; j++)
{
btnUpload = new Button();
btnUpload.Width = 100;
btnUpload.Text = "Upload";
btnUpload.ID = btnUpload.Text;
rcell.Controls.Add(btnUpload);
btnUpload.Click += new EventHandler(UpLdButton_Click);
}
rrow.Cells.Add(rcell);
}
table.Rows.Add(rrow);
}
CTflag = true;
ViewState["dynamictable"] = true;
cn.Close();
myReader.Close();
}
}
protected void UpLdButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < tblRow; i++)
{
fileUp = (FileUpload)FindControlRecursive(this, string.Format("fileUpLoader{0}{1}", 0, i));
//rest of code to save file
}
}
Why don't you use asp repeater to display FileUploads?
you can easily set the html template and design, as DataSource use DataTable of your data
<asp:repeater id='rp' runat='server'>
<ItemTemplate>
<%Eval("UploadType"%> -this is the caption
<asp:fileUpload id='file' runat='server'/>
<asp:Button id='btnUpload' onclick='UploadClick' runat='server'/>
</ItemTemplate>
protected void lstLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
{
//get data into DataTable
rp.DataSource=dt;
rp.DataBnd();
}
protected void UpLdButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < tblRow; i++)
{
//this way you get the relevant fileUpload
fileUp = (FileUpload)((Button)Sender).Parent.FindControl ("file);
//rest of code to save file
}
}
You were on the right track when you added the dynamic buttons in the OnInit event - you just needed to also add the FileUpload controls too.
All of the controls need to be recreated on every postback. .NET automatically handles the controls you added to the ASPX page. You are responsible for the dynamic controls you add programmatically.
Here are a couple of approaches you can take from where you are:
Continue with dynamically adding the control but make the change so you are adding all of the controls, not just the buttons.
If you have a known maximum to the number of controls then you could add then all and control what is displayed using the Visible property. This works when the number of controls is small. It looks like you are putting borders around the table cells so this would not look so good in your case. If you can change the layout so that hiding the controls does not result in residual artifacts then this is an option.

How to add a dynamically link in a dynamically added table

I'm a newbie and struggle to add a link, showed like an img in a dynamically added table.
string search = Search.Text;
IMyData members = new MyData();
DataTable dt = new DataTable();
dt = members.Search(search);
Table t = new Table();
t.ID = "tblTable";
TableRow row = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
HyperLink link = new HyperLink();
row = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell cell = new TableCell();
if (j == dt.Columns.Count - 1) //This last field may hava a number
{
if (Convert.ToInt32(dt.Rows[i][j].ToString()) > 0)
{
link.ID = "link" + i + "_" + j;
link.NavigateUrl = "members.aspx?showLease=" + dt.Rows[i][j].ToString();
link.ImageUrl = "img/document.png";
Page.Controls.Add(link); // How to put this in a cell, not on page
}
else
{
cell.Text = dt.Rows[i][j].ToString();
}
}
row.Cells.Add(cell);
}
t.Rows.Add(row);
}
pnlTable.Controls.Add(t);
How can I put the Hyperlink to the cell, and not to the Page?
Thanks
You can add control in TableCell the way you are doing in Page. Change your code like this
Page.Controls.Add(link);//Will add control in page
cell.Controls.Add(link);//Will add control in table cell
See below, I changed Page.Controls.Add(link) to cell.Controls.Add(link) and moved your Hyperlink declaration into the cell loop. Otherwise if will only be added in the last cell.
But if I see your code it seems that only the last cell will have link or text because of the j == dt.Columns.Count - 1
for (int i = 0; i < dt.Rows.Count; i++) {
row = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
HyperLink link = new HyperLink();
TableCell cell = new TableCell();
if (j == dt.Columns.Count - 1) //This last field may hava a number
{
if (Convert.ToInt32(dt.Rows[i][j].ToString()) > 0)
{
link.ID = "link" + i + "_" + j;
link.NavigateUrl = "members.aspx?showLease=" + dt.Rows[i][j].ToString();
link.ImageUrl = "img/document.png";
cell.Controls.Add(link); // How to put this in a cell, not on page
}
else
{
cell.Text = dt.Rows[i][j].ToString();
}
}
row.Cells.Add(cell);
}
t.Rows.Add(row);
}

Dynamic Table cell to be filled when triggering a method

I'm working with ASP.NET an C# I have a dynamic table and I want a cell to have an initial value then I want to use this value as a parameter in a method and fill the same cell with another value....
here is snippet of my code
for (int index = 0; index < size; index++) {
List<Hotel> h = listHotelList[index];
Hotel myHotel = new Hotel();
mytable = new Table();
mytable.ID = "HotelTable"+index;
Page.Form.Controls.Add(mytable);
mytable.CellSpacing = 20;
mytable.CellPadding = 10;
for (int g = 0; g < h.Count; g++)
{
myHotel = h[g];
TableRow row = new TableRow();
for (int i = 0; i < 2; i++)
{
TableCell cell = new TableCell();
if (i == 0)
{
// I want to leave this with only the value of the hotelId
// and I want my method to fill this cell with an image by retrieving
// the value of the hotelId
}
if (i == 1)
{
Label tb = new Label();
tb.ID = "label1_" + g + "Col" + i;
tb.Text = "<h4>" + myHotel.hotelName + "</h4><br />";
cell.Controls.Add(tb);
}
row.Cells.Add(cell);
}
mytable.Rows.Add(row);
}
}
for my case I'm taking a hotel Id from the cell when the user click a button then it trigger a method that would take the value in the cell "hotel Id" and retrieve the image for this particular hotel and fill the cell with the image
Is the problem that you don't see the tabel?
If so,
add the table to your page
Page.Controls.Add(mytable);
If the positioning is not good, then put a placeholder on your page, and add the control there.
Placeholder.Controls.Add(mytable);

how can I reach radiobuttonlist?

I write this codes :
TabContainer TabContainer1 = new TabContainer();
TabContainer1.ID = "TabContainer1";
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
for (int toplam_grp = 0; toplam_grp < 1; toplam_grp++)
{
Panel my_panel= new Panel();
my_panel.ID = toplam_grp + "my_panel";
for (int j = 0; j < 10; j++)
{
Label my_label = new Label();
my_label.ID = j + 10 * toplam_grp + "mylabel";//burda 10 j nin sınırı olcak
my_label.Text = "asdasdas";
RadioButtonList radioButtonList = new RadioButtonList();
radioButtonList.ID = j + 10 * toplam_grp + "radioButton";
radioButtonList.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
for (int i = 0; i < 5; i++)
{
radioButtonList.Items.Add(((char)(i + 65)).ToString());
}
my_panel.Controls.Add(my_label); /////////////////////////burda yanyana gözükse daha iyi olur
my_panel.Controls.Add(radioButtonList);
}
TabPanel tab = new TabPanel();
tab.ID = toplam_grp+"tab1";
tab.HeaderText =toplam_grp+"nbr";
TabContainer1.Tabs.Add(tab);
TabContainer1.Tabs[toplam_grp].Controls.Add(my_panel);
}
cell.Controls.Add(TabContainer1);
row.Cells.Add(cell);
myplace.Rows.Add(row);
I create a tabcontainer and one tab and in tab I create 10 radiobuttonlist(I give them ids each one) which have 5 members.
And I write this code to reach radiobuttonlist but ı dont reach because dont find their ids :
string ss = "";
for (int i = 0; i < 10; i++)
{
ss += ((RadioButtonList)(FindControl(i + "radioButton"))).SelectedIndex + "\n";
}
MessageBox.Show(ss);
for example first radiobuttonlist id : 0radioButton but it cant found.What can I do.Thanks for answering...
The whole code is a little confusing for me but I try to add my 2 cents.
You need to execute FindControl against the RadiobuttonList container and not against the page.
So, for instance, if you added a control named RadioButtonList1 to a asp.net panel named Panel1 you would have to do
Panel1.FindControl("RadioButtonList1 ")

Categories

Resources