Dynamic Table in asp.net design - c#

I built recently a table using c# and asp.net and I was facing design issues.
string name = Request.QueryString["name"];
AnimalsDB animal = new AnimalsDB();
DataSet ds = animal.GetFactByName(name);
TableRow rw = new TableRow();
TableCell tc1 = new TableCell();
Label l1 = new Label();
l1.Text = ds.Tables[0].Rows[0]["AName"].ToString();
Image image = new Image();
image.ImageUrl = ds.Tables[0].Rows[0]["Pic"].ToString();
image.Width = 250;
image.Height = 250;
Label l2 = new Label();
l2.Text = ds.Tables[0].Rows[0]["Fact"].ToString();
tc1.Width= 200;
tc1.Controls.Add(l1);
tc1.Controls.Add(image);
tc1.Controls.Add(l2);
rw.Cells.Add(tc1);
Table3.Rows.Add(rw);
The table is bit unorganized all the details appears on one line, do you have any idea how to sort it and organize the details.
(In my case I want to show the lable1 break-line image and break-line then the 2nd lable).

If all you have to display is three pieces of information, try something like this for your front end:
<h3><asp:Label ID="_animalName" runat="server"></asp:Label></h3>
<asp:Image ID="_animalImg" runat="server" />
<p><asp:Label ID="_animalFact" runat="server"></asp:Label></p>
And then your code behind:
_animalName.Text = ds.Tables[0].Rows[0]["AName"].ToString();
_animalImg.ImageUrl = ds.Tables[0].Rows[0]["Pic"].ToString();
_animalFact.Text = ds.Tables[0].Rows[0]["Fact"].ToString();

Related

Add Ajax CalendarExtender to a dynamic textBox in ASP.NET C#

Is there a way to add Ajax CalendarExtender to a dynamic ASP.NET textbox control? Basically I'm trying to do the following:
protected void Page_Load(object sender, EventArgs e)
{
database.DB myDB = new database.DB();
DataTable myVars = new DataTable();
string myTopicID = (string)Session["myTopicID"];
bool myInvite = (bool)Session["myInvite"];
bool mySig = (bool)Session["mySig"];
string myLogo = (string)Session["myLogo"];
string myImage = (string)Session["myImage"];
string myLanguage = (string)Session["myLanguage"];
myVars = myDB.getVarFields(myTopicID, myLanguage);
AjaxControlToolkit.CalendarExtender calenderDate = new AjaxControlToolkit.CalendarExtender();
for (int i = 0; i < myVars.Rows.Count; i++)
{
Label label = new Label();
TextBox text = new TextBox();
label.Text = Convert.ToString(myVars.Rows[i]["varName"]);
myPlaceHolder.Controls.Add(label);
text.ID = Convert.ToString(myVars.Rows[i]["varName"]);
myPlaceHolder.Controls.Add(new LiteralControl(" "));
myPlaceHolder.Controls.Add(text);
if (Convert.ToString(myVars.Rows[i]["varName"]).Contains("Date:"))
{
calenderDate.TargetControlID = "ContentPlaceHolder1_" + text.ID;
myPlaceHolder.Controls.Add(calenderDate);
}
myPlaceHolder.Controls.Add(new LiteralControl("<br />"));
}
}
The error I get when I run the code above is the following:
The TargetControlID of '' is not valid. A control with ID 'ContentPlaceHolder1_Date:' could not be found.
Which makes sense I suppose since the actual text box does not exist yet. But is there a way around this?
I think ASP.NET will be smart enough to handle it if you just use text.ID, you shouldn't need to add the ContentPlaceHolder1_ prefix.
If that doesn't work, you can use the TextBox' ClientIdMode property to set it to static, then text.ID will definitely work.
The following code worked locally for me:
AjaxControlToolkit.CalendarExtender calenderDate = new AjaxControlToolkit.CalendarExtender();
for (int i = 0; i < 2; i++)
{
Label label = new Label();
TextBox text = new TextBox();
label.Text = Convert.ToString("varName");
ph1.Controls.Add(label);
text.ID = "myId" + i;
ph1.Controls.Add(new LiteralControl(" "));
ph1.Controls.Add(text);
calenderDate.TargetControlID = text.ID;
ph1.Controls.Add(calenderDate);
ph1.Controls.Add(new LiteralControl("<br />"));
}
Only differences I think you may want to investigate: I'm using latest ControlToolkit from Nuget, I'm using a ToolkitScriptManager instead of default ScriptManager. One thing that may be important to you is making sure you make text.ID unique.

How to set MS Chart LegendItem image size

I use Image from Resources to LegendItem in WinForms
var ImageName = "ImageName";
myChart.Images.Add(new NamedImage(ImageName, Resources.Image));
LegendItem legendItem = new LegendItem();
legendItem.Name = "legend text";
legendItem.Image = ImageName;
myChart.Legends[Legend.Name].CustomItems.Add(legendItem);
But the size of Image is too small.
How can I change it?
You should use custom LegendCell in this case. This means you define the cells for your LegendItem specifying their properties. Something like this:
LegendItem legendItem = new LegendItem();
LegendCell cell1 = new LegendCell();
cell1.Name = "cell1";
cell1.Text = "legend text";
// here you can specify alignment, color, ..., too
LegendCell cell2 = new LegendCell();
cell2.Name = "cell2";
cell2.CellType = System.Windows.Forms.DataVisualization.Charting.LegendCellType.Image;
cell2.Image = "path of your img";
cell2.Size = new Size(.....);
legendItem.Cells.Add(cell1);
legendItem.Cells.Add(cell2);

ASP.NET -> Adding a ButtonColumn to a DataTable or DataGridView (Programmatically)

Having the odd problem figuring out how to add a ButtonColumn to a DataTable (or, arguably, the DataGrid). All I want to do is be able to use the data from the datatable to tell a button to do something onClick, and I seem to be failing at it.
A google search did not show anything immediately useful, as they are all using ItemTemplates.
//dt.Columns.Add("Ajax Link", typeof(Literal));
ButtonColumn newButtonColumn = new ButtonColumn();
newButtonColumn.HeaderText = "Asp.Net Link";
dt.Columns.Add(); // Doesn't want newButtonColumn.
for (int i = 0; i < dt.Rows.Count; i++)
{
/*
Literal newAjaxLink = new Literal();
newAjaxLink.Text = "Test";//"<button type=\"button\" onclick=\"AjaxButton_onClick(" + dt.Rows[i]["UserInfoID"].ToString() + "); StoreUserInfoID(" + dt.Rows[i]["UserInfoID"].ToString() + "); ShowDiv();\">Ajax Link</button>";
dt.Rows[i]["Ajax Link"] = newAjaxLink; // #todo: HTML button that triggers an AJAX call for load the proper data into the fields. Also to make the DIV visible.
*/
Button newButton = new Button();
newButton.ID = dt.Rows[i]["UserInfoID"].ToString();
newButton.Text = "Asp.Net Link";
newButton.Click += new EventHandler(Button_Link_Click);
dt.Rows[i]["Asp.Net Link"] = newButton; //#todo: Just a button to open a new window with the proper ID.
}
Any ideas?
where are u adding the button to the respective thing?...seems u r just giving values to button,but not adding.
Try this
DataTable dt = new DataTable("Table");
DataColumn col = dt.Columns.Add("ID", typeof(Int32));
col.AllowDBNull = true;

How to dynamically generate html with .ascx?

I have some settings stored in web.config like this:
<add key="Answers" value="radiobutton1,radiobutton2,radiobutton3"/>
Radiobutton1, radiobutton2 and radiobutton3 are radiobutton label values.
In settings.cs I have a function to retrieve value from web.config:
public static string Answers
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["Answers"];
}
}
.ascx file:
<table runat="server" OnPreRender="Radio_PreRender" id="table1" name="table1">
</table>
My ascx.cs file contains this function:
protected void Radio_PreRender(object sender, EventArgs e)
{
if (Settings.Answers != "")
{
int counter = 0;
string a = Settings.Answers;
string[] words = a.Split(',');
StringWriter stringwriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
foreach (string word in words)
{
writer.WriteBeginTag("tr");
writer.WriteBeginTag("td");
writer.Write("abc123");
RadioButton rdb1 = new RadioButton();
rdb1.Checked = true;
rdb1.GroupName = "rdbgroup";
rdb1.ID = "radiobutton" + counter;
rdb1.Text = word;
table1.Controls.Add(rdb1 );
writer.WriteEndTag("td");
writer.WriteBeginTag("tr");
table1.Render(writer);
counter++;
}
}
}
In other words, I want to generate a dynamic number of this code inside table1:
<tr>
<td>
// input type="radiobutton" and label go here.
</td>
</tr>
At the moment radiobuttons are not generated, because they can't be direct child elements to a table. If I specify a div instead, radiobuttons are generated, but everything I try to write with HtmlTextWriter is not. I understand that my html has to be rendered by using table1.Render(writer); or something similar, but I can't figure it out.
You can try creating a table and add it to the page you are working on, using the exmaple below you can replace the textbox with a radiobutton
Here is an example:
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
I do this quite often by running the user control through its full asp.net lifetime and getting it as a string:
http://www.diaryofaninja.com/blog/2009/09/14/a-simple-solution-to-viewing-a-preview-of-any-page-in-your-site
This way you can use ASP.Net as a templating engine for anything
Page tempPage = new Page();
UserControl myUserControl = new MyUserControl();
tempPage.Controls.Add(myUserControl);
StringWriter sw = new StringWriter();
HttpContext.Current.Server.Execute(tempPage, sw, false);
if (!String.IsNullOrEmpty(sw.ToString()))
{
return sw.ToString();
}

get dynamically generated ajax textbox id

I have created a web application in which I need to generate textboxes depending upon the number the user enters.I have used Ajax and created textboxes dynamically but these textboxes are not accessible from code-behind.I have used find control but to no use.This is the code I use to generate textbox.
if (txtnobranches.Text != "")
{
if (Convert.ToInt32(txtnobranches.Text) != 0)
{
div_br.InnerHtml = "<table></table>";
tbl_br.Controls.Clear();
for (int i = 0; i < Convert.ToInt32(txtnobranches.Text); i++)
{
TableRow rowbr = new TableRow();
TableCell cellname = new TableCell();
cellname.Text = "Branch Location " + i.ToString();
rowbr.Cells.Add(cellname);
TableCell cellvalue = new TableCell();
cellvalue.Text = "";
TextBox txt = new TextBox();
txt.Text = "";
txt.ID = "txtbranchloc" + i.ToString();
cellvalue.Controls.Add(txt);
cellvalue.ID = "txtbranchloc" + i.ToString();
rowbr.Cells.Add(cellvalue);
tbl_br.Rows.Add(rowbr);
}
}
}
You can access the element by name using Request.Form["NameOfFormControl"] You will have to make little change in code.
In javascript
txt.Name = "txtbranchloc" + i.ToString();
In Code Behind
Note: Make sure you access it in postback otherwise you get null
if (Page.IsPostBack)
{
string firstTxtVal = Request.Form["txtbranchloc0"].ToString();
string secondTxtVal = Request.Form["txtbranchloc1"].ToString();
}
Using Request.Form Collection

Categories