Adding controls programmatically - c#

I am creating ASP.NET wep page. I have a world map and I want to add some image buttons (cities) controls in C#. I made the method:
I am using stored procedure to get data from database but when I add next city to the procedure the previously added imagebutton changes its position.
private void LocateCities()
{
IDBManager dbManager = new DBManager(DataProvider.SqlServer);
dbManager.ConnectionString = #"Data Source=server; Initial Catalog=db; Integrated Security = SSPI;";
try
{
dbManager.Open();
dbManager.CreateParameters(2);
dbManager.AddParameters(0, "#Function", "All");
dbManager.AddParameters(1, "#Team", "All");
DataSet ds = new DataSet("Stuff");
ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "sp_select_staff_and_cities");
foreach (DataRow dr in ds.Tables[0].Rows)
{
int xaxis = Convert.ToInt32(dr["xaxis"]) ;
int yaxis = Convert.ToInt32(dr["yaxis"]) ;
int textxaxis = xaxis + 30;
int textyaxis = yaxis - 10;
ImageButton btnCity = new ImageButton();
btnCity.ImageUrl = "~/Images/cyanball1.gif";
btnCity.Height = 10;
btnCity.Attributes.Add("style", "Z-INDEX:100; POSITION:relative; left:" + xaxis + "px; TOP:" + yaxis + "px; Left:10px;Right:10px");
Label lblCity = new Label();
lblCity.Text = dr["city"].ToString();
lblCity.Attributes.Add("style", "Z-INDEX: 100;POSITION:relative; left:" + textxaxis + "px; TOP:" + textyaxis + "px");
PanelMap.Controls.Add(lblCity);
PanelMap.Controls.Add(btnCity);
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
dbManager.Dispose();
}
}
I am using panel to keep image with map:
.PanelMap
{
width:960px;
height:572px;
text-align:left;
}
What should be changed in above code to keep the points in its place?
I tried to use position:absolute but it cause that posiotion is derived relative to the page and I would like it would be derived relatively to the panel control.

The problem would be this, POSITION:relative, so change that to POSITION:absolute on both lines and you'll be good.

Related

out of memory exception with grid in scrollviewer

I am very new in developing apps with C# for WP 8.1 Silverlight.
I developed an app to display data from a csv-file.
The data is displayed in a grid within a scrollviewer element with 7 columns.
All works fine. But when the app gets more then 600 lines from the csv-file the app crashes with an out of Memory exception.
How can I avoid this? It should be no problem to display 600 lines of text in a grid.
See my code:
//insert lines:
//Row create:
reihe1 = new RowDefinition();
reihe1.Height = new GridLength(zeilenhoehe);
grid_umsatzdetail.RowDefinitions.Add(reihe1);
reihe1 = null;
//Columns create:
//first column date:
textblock_name = dateizeile + "|" + index_daten + "|" + "0";
TextBlock textblock_new_datum = new TextBlock();
textblock_new_datum.Name = textblock_name;
textblock_new_datum.Height = zeilenhoehe;
textblock_new_datum.Width = Double.NaN;
textblock_new_datum.FontSize = schriftgroesse;
textblock_new_datum.Text = " " + teile[0] + " ";
Grid.SetRow(textblock_new_datum, zaehler_reihe);
Grid.SetColumn(textblock_new_datum, 0);
grid_umsatzdetail.Children.Add(textblock_new_datum);
textblock_new_datum = null;
//border insert into grid:
rand = new Border();
rand.BorderThickness = new Thickness(1);
rand.BorderBrush = new SolidColorBrush(Colors.White);
rand.Width = Double.NaN;
rand.Height = zeilenhoehe_head;
Grid.SetRow(rand, zaehler_reihe);
Grid.SetColumn(rand, 0);
grid_umsatzdetail.Children.Add(rand);
rand = null;
//second column amount:
... same coding as above for every column ...
I am really happy for any tips!

Using a variable to access a chart

I have a C# WinForms application that has four chart controls used to graphically show some analysis results.
I have the code working for each graph, however in an attempt to be more efficient & re-use code I've defined a code block to:
create the required series,
extracts the data from a database & assigns the results to the appropriate series
add the series to the chart
customise the charts appearance.
All of the above is done dynamically as the data does not exist at design time.
The working code I am looking to re-use is:
// Add both series to the chart.
ChartName.Series.AddRange(new Series[] { series1, series2 });
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)ChartName.Diagram;
I'd like to change the ChartName object to a variable that I can pass each of the charts in order to re-use the code. Something like (note this does not work):-
var VChart = this.Controls.Find(ChartName, true);
// Add both series to the chart.
VChart.Series.AddRange(new Series[] { series1, series2 });
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)VChart.Diagram;
Any ideas, hints, tips, etc on how-to pass a variable into the ChartName would be appreciated.
Full Code:
void Generate_Chart()
{
// Create two stacked bar series.
Series series1 = new Series("Data", ViewType.Bar);
Series series2 = new Series("Ben", ViewType.Line);
try
{
using (var cmd = new SQLiteCommand(m_dbConnection))
for (int i = LoopMin; i < LoopMax; i++)
{
// Retrieve the actual calculated values from the database
cmd.CommandText = "SELECT " + Chart_SourceActualValue + " FROM " + Chart_SourceTable + " WHERE Value = " + i + "";
Chart_SeriesA_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Retrieve the expected values from the database
cmd.CommandText = "SELECT " + Chart_BenExpValue + " FROM " + Chart_SourceTable + " WHERE Value = " + i + "";
Chart_SeriesB_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Add the dynamically created values to a series point for the chart
series1.Points.Add(new SeriesPoint(i, Chart_SeriesA_Value));
series2.Points.Add(new SeriesPoint(i, Chart_SeriesB_Value));
}
}
catch (Exception)
{
throw;
}
// Add both series to the chart.
//this.Controls.Find(varChart, true)
ChartName.Series.AddRange(new Series[] { series1, series2 });
// Remove the GridLines from the chart for better UI
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)ChartName.Diagram;
// Customize the appearance of the axes' grid lines.
diagram.AxisX.GridLines.Visible = false;
}
}
It sounds like you're asking to replace the hardcoded ChartName with a variable so that you can call your routine four different times, each time with a different chart. I've taken your code and replaced some of the global variable of your chart control and settings and and made them parameters you pass into the function:
void Generate_Chart(DevExpress.XtraCharts.ChartControl chartCtrl,
string chart_sourceActualValue,
string chart_sourceTable,
string chart_benExpValue
)
{
// Create two stacked bar series.
Series series1 = new Series("Data", ViewType.Bar);
Series series2 = new Series("Ben", ViewType.Line);
try
{
using (var cmd = new SQLiteCommand(m_dbConnection))
for (int i = LoopMin; i < LoopMax; i++)
{
// Retrieve the actual calculated values from the database
cmd.CommandText = "SELECT " + sourceActualValue + " FROM " +
chart_sourceTable + " WHERE Value = " + i + "";
Chart_SeriesA_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Retrieve the expected values from the database
cmd.CommandText = "SELECT " + chart_benExpValue + " FROM " +
chart_sourceTable + " WHERE Value = " + i + "";
Chart_SeriesB_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Add the dynamically created values
// to a series point for the chart
series1.Points.Add(new SeriesPoint(i, Chart_SeriesA_Value));
series2.Points.Add(new SeriesPoint(i, Chart_SeriesB_Value));
}
}
catch (Exception)
{
throw;
}
// Add both series to the chart.
chartCtrl.Series.AddRange(new Series[] { series1, series2 });
// Remove the GridLines from the chart for better UI
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)chartCtrl.Diagram;
// Customize the appearance of the axes' grid lines.
diagram.AxisX.GridLines.Visible = false;
}
}
Then, you end up calling this method like this using the original values as arguments:
void Generate_Chart(ChartName, Chart_SourceActualValue, Chart_SourceTable,
Chart_BenExpValue);
// call it three other times passing in the different specifics for that chart. e.g.
void Generate_Chart(SomeOtherChartName, SomeOtherChart_SourceActualValue,
SomeOhterChart_SourceTable, SomeOtherChart_BenExpValue);
.....

Creating run time textbox in Windows Phone 7

I wanted to display no of course json objects in each textbox
but as they are unpredictable number of objects therefore i created textbox on the fly using this code
List<Course> Cdata = JsonConvert.DeserializeObject<List<Course>>(App.data);
TextBox[] Tblock = new TextBox[Cdata.Count];
double top = 0; int i = 0;
foreach (Course de in Cdata)
{
result += de.course_name + "\r\n";
result += "Total Absents = " + de.absents;
result += " + " + de.presents;
result += " = " + de.sessions + "\r\n\r\n\r\n";
Tblock[i] = new TextBox();
Tblock[i].Text = result;
Tblock[i].AcceptsReturn = true;
Tblock[i].TextWrapping = TextWrapping.Wrap;
Tblock[i].Width = 475;
Tblock[i].Height = 270;
Tblock[i].IsReadOnly = true;
Tblock[i].Margin =new Thickness (0,top,0,0);
Tblock[i].Visibility = System.Windows.Visibility.Visible;
Tblock[i].VerticalAlignment = System.Windows.VerticalAlignment.Top;
top += 270; i++;
result = "";
}
Now when i debug my app data it is working as its supposed to the only problem is textbox
never display on View
and i haven't coded any textbox in Xaml file of view
Thanks in Advance
You have to add the Textboxes to any existing Panel (generally to Grid or StackPanel) in the XAML as shown below
StackPanel sp = new StackPanel(); //Create stack panel before foreach loop
foreach (Course de in Cdata)
{
//your code which you shown above
sp.Children.Add(Tblock[i]); //Add all the Textboxes to the stackpanel
}
ContentPanel.Children.Add(sp); //And add the above stackpanel to the existing Grid named ContentPanel
By the way, I suggest you to use a ListBox with ItemTemplate to bind the data instead of creating the TextBoxes as shown above.
Also, I don't understand why you have choosen TextBox instead of TextBlock to display data

Scope of a LiteralControl problem

I have a piece of code that creates dynamic controls using 2 while loops.
As you can see, I am forced to declare both LiteralControls INSIDE each while loop because if I don't, the puBugList.Controls.Add(lineBreak) will not acknowledge.
Q: Why can I not see the scope of the controls from inside a while loop?
//this control is not acknowledged
//LiteralControl lineBreak = new LiteralControl("<br/>");
while (nwReader.Read())
{
int id = (int)nwReader["bid"];
string user = (string)nwReader["buname"];
string prob = (string)nwReader["bproblem"];
string content = id + ". " + user + ": " + prob + "<br/>";
Label lb = new Label();
lb.Text = content;
phBugList.Controls.Add(lb);
//forced to declare 1 here
LiteralControl lineBreak = new LiteralControl("<br/>");
String sqlSelRep = "SELECT * FROM [reply] WHERE bid=#bid";
SqlCommand cmdSelRep = new SqlCommand(sqlSelRep, conn);
cmdSelRep.Parameters.AddWithValue("#bid", id);
SqlDataReader repReader = cmdSelRep.ExecuteReader();
while (repReader.Read())
{
//forced to declare another
LiteralControl lineBreak2 = new LiteralControl("<br/>");one here
string msg = (string)repReader["rmsg"];
Label lbRep = new Label();
lbRep.Text = "Admin: \"" + msg + "\"";
phBugList.Controls.Add(lbRep);
phBugList.Controls.Add(lineBreak2);
}
repReader.Close();
if (Convert.ToInt32(Session["user"]) == 1)
{
phBugList.Controls.Add(lineBreak);
TextBox tbRep = new TextBox();
tbRep.ID = "tb" + id.ToString();
phBugList.Controls.Add(tbRep);
LinkButton butRep = new LinkButton();
butRep.ID = "rep" + id.ToString();
butRep.Text = " Reply";
butRep.Click += InsertReply;
phBugList.Controls.Add(butRep);
LinkButton butDel = new LinkButton();
butDel.ID = "del" + id.ToString();
butDel.Text = " Delete";
butDel.Click += DeleteBug;
phBugList.Controls.Add(butDel);
phBugList.Controls.Add(lineBreak);
}
phBugList.Controls.Add(lineBreak);
}
I think you'r problem is that if you instantiate LiteralControl outside the while loop you are effectively using the same object throughout your code, and you cannot add the same control twice to a Controls collection of another control.
Try the following:
LiteralControl lineBreak = null;
(...)
while (repReader.Read())
{
literalControl = new LiteralContro(...);
}
Anyway, unless you need lineBreak in scope outside the while loop there is nothing wrong declaring the variable inside the loop so your code is perfectly fine.

Add textbox via dynamic imagebutton in a panel

I have a problem I seem to stumble over all the time, I have a Drop Down box and you can select a number which creates x number of textboxes with images buttons its for a survey it the image buttons are used to create "Sub-Answers" so they can have answers to answers so my question is I need to when they hit the image button to create a textbox under the orginal textbox here is the code.
for (Int32 i = 1; i <= NumberOfAnwsers; i++)
{
Literal l1 = new Literal();
l1.Text = "<tr><td>Answer " + i + " text.</td><td>";
TextBox tb = new TextBox();
tb.ID = "TextBoxAnswer" + i;
tb.EnableViewState = false;
tb.Width = 300;
Literal l3 = new Literal();
l3.Text = "</td><td>";
Literal l2 = new Literal();
l2.Text = "</td></tr>";
RadColorPicker CPI = new RadColorPicker();
CPI.PaletteModes = PaletteModes.WebPalette;
CPI.ID = "RadColorPicker" + i;
CPI.ShowIcon = true;
CPI.SelectedColor = System.Drawing.Color.Black;
ImageButton IBVideo = new ImageButton();
IBVideo.ID = "IBVideo" + i;
IBVideo.ImageUrl = "/images/video-icon.jpg";
IBVideo.ToolTip = "Add Video";
IBVideo.Height = 20;
IBVideo.Width = 20;
ImageButton IBAdd = new ImageButton();
IBAdd.ID = "IBAdd" + i;
IBAdd.ImageUrl = "/images/add-icon.png";
IBAdd.ToolTip = "Add Sub-Answers";
//IBAdd.OnClientClick = "showDialog(" + i + ");return false;";
IBAdd.Height = 20;
IBAdd.Width = 20;
//Add Textbox
PanelAnswersToQuestions.Controls.Add(l1);
PanelAnswersToQuestions.Controls.Add(tb);
PanelAnswersToQuestions.Controls.Add(l3);
PanelAnswersToQuestions.Controls.Add(CPI);
PanelAnswersToQuestions.Controls.Add(IBVideo);
PanelAnswersToQuestions.Controls.Add(IBAdd);
PanelAnswersToQuestions.Controls.Add(l2);
}
As you can see I just add controls to the panel, I need to know when that ImageBUtton is hit I can add a Textbox and in this case it could be more then just one textbox to it.
I hope this is clear but for some reason I dont think it is ... sorry.
I have added a radwindow and poping that up sending the Data to the partent via javascript the which created a new problem for me, I can not in javascript seem to find the dynamicly created hiddenfield
function OnClientClose(radWindow) {
var oWnd = $find("<%=RadWindowAddSubAnswer.ClientID%>");
var SubAnswerValues = oWnd.get_contentFrame().contentWindow.document.forms(0).HiddenFieldSubAnswers.value;
alert(SubAnswerValues);
var AnswerID = oWnd.get_contentFrame().contentWindow.document.forms(0).HiddenFieldAnswerID.value;
alert(AnswerID);
var HiddenName = "HiddenFieldSubAnswers" + AnswerID;
alert(HiddenName);
document.getElementById(HiddenName).value = SubAnswerValues;
$get("DivSubAnswers" + AnswerID).innerHTML = SubAnswerValues;
}
The "document.getElementById(HiddenName).value = SubAnswerValues;" seems to never be found, I also tried $get(HiddenName).value = SubAnswerValues; that does not seem to work either both come back as null as for the code behind its:
HiddenField HFSubAnswers = new HiddenField();
HFSubAnswers.ID = "HiddenFieldSubAnswers" + i;
HFSubAnswers.Value = "0";
Im not sure if I got your question right but if you need to dynamically add controls on a Page here is what I can say.
Before adding your control I guess you need to find the control where you need to add it on, Add the control then assign the properties.
PlaceHolder myPlaceHolder = (PlaceHolder)Page.FindControl("PlaceHolder1");
myPlaceHolder.Controls.Add(myButton);
myButton.Text = "Hello World";
For a more detailed expalnation go here http://anyrest.wordpress.com/2010/04/06/dynamically-removing-controls-in-a-parent-page-from-a-child-control/

Categories

Resources