I have been developing an application using winforms c# .net 4.0.
this application use datagridview and i add combobox + textbox to the datagridview.
During binddata and resizing actions, a black rectangle will draw in the bottom portion of the datagridview.
see the image of the problems
it works perfectly on standard DPI, but problem on the high DPI.
here is the some of my code to binddata and resizing.
using (Class1.Connection = new OleDbConnection(Class1.ConnString))
{
string sql1 = "SELECT tbAuditDetails.AuditNo, tbAuditQuestions.AutoSubcontent, tbAuditQuestions.AutoID, tbAuditQuestions.Questions, tbScore.Description, tbAuditDetails.QuestionID, tbAuditQuestions.QuestAutoID, tbAuditDetails.ScoreID, tbScore.Score, tbAuditQuestions.SubContentID, tbAuditDetails.ProfileID, tbAuditDetails.ScoreRanges, tbAuditDetails.Comments FROM (tbAuditDetails INNER JOIN tbAuditQuestions ON tbAuditDetails.QuestionID = tbAuditQuestions.QuestionID) INNER JOIN tbScore ON tbAuditDetails.ScoreID = tbScore.ScoreID WHERE (([tbAuditDetails.AuditNo] = " + Class1.detailsauditno + ") AND ([tbAuditQuestions.AutoSubcontent] = '" + newautosubcontentid + "') AND ([tbAuditDetails.ProfileID] = " + proid + ")) ORDER BY [tbAuditQuestions.QuestAutoID], [tbAuditDetails.QuestionID]";
Class1.Connection.Open();
oleCommand = new OleDbCommand(sql1, Class1.Connection);
oleAdapter = new OleDbDataAdapter(oleCommand);
oleBuilder = new OleDbCommandBuilder(oleAdapter);
oleDs = new DataSet();
oleAdapter.Fill(oleDs, "tbAuditDetails");
oleTable = oleDs.Tables["tbAuditDetails"];
Class1.Connection.Close();
dataGridView1.DataSource = oleDs.Tables["tbAuditDetails"];
//SET DATAGRIDVIEW
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[8].Visible = false;
dataGridView1.Columns[9].Visible = false;
dataGridView1.Columns[10].Visible = false;
dataGridView1.Columns[1].HeaderText = " ";
dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[1].Width = 40;
dataGridView1.Columns[2].HeaderText = "ID";
dataGridView1.Columns[2].Width = 40;
dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].Width = 600;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[3].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Columns[11].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[11].HeaderText = "Score";
dataGridView1.Columns[12].Width = 220;
for (int iii = 0; iii < dataGridView1.Rows.Count; iii++)
{
DataGridViewComboBoxCell ComboBoxCell2 = new DataGridViewComboBoxCell();
ComboBoxCell2.Items.Add("0");
ComboBoxCell2.Items.Add("10");
ComboBoxCell2.Items.Add("20");
ComboBoxCell2.Items.Add("30");
ComboBoxCell2.Items.Add("40");
ComboBoxCell2.Items.Add("50");
ComboBoxCell2.Items.Add("60");
ComboBoxCell2.Items.Add("70");
ComboBoxCell2.Items.Add("80");
ComboBoxCell2.Items.Add("90");
ComboBoxCell2.Items.Add("100");
//ComboBoxCell.Items.AddRange(new string[] { "YES", "SOME", "NO", "N/A" });
ComboBoxCell2.FlatStyle = FlatStyle.Standard;
this.dataGridView1[11, iii] = ComboBoxCell2;
ComboBoxCell2.Dispose();
}
}
Any suggestions?
I don't know this is the right solution or not...
BUT, it fix my problem.
Here :
Right click on the .exe program (after you build) and Disable HIGH DPI
Related
I'm working on stimulsoft 2017.2.2 and C# (.NET4).
I have designed a report with footer and header , It is A4 and there is a table in it , based on stimulsofts method(DataGrid) to create a table at runtime I managed to change it to a report which accepts DataTable and everything works just fine on an empty project (.mrt file).
There is a table so i want to customize it there , Call it and customize it at runtime.
The problem is when I want to add this to my own file (.mrt) the table is empty , it only has 1 column and the rows are fine , the whole table is empty but the design is visible.
So I will really appreciate If you could help me to sort this problem out.
My method looks like this :
private void PrintDataTable(string StiTableName, string DataSourceName, DataTable dataTable, StiReport report)
{
DataView dataView = new DataView(dataTable);
report.Compile();
//script lang
report.ScriptLanguage = StiReportLanguageType.CSharp;
// Add data to datastore
report.RegData(DataSourceName, dataView);
// Fill dictionary
report.Dictionary.Synchronize();
//StiPage page = report.Pages.Items[0];
// Create Table
StiTable table = (StiTable)report[StiTableName];
//StiTable table = (StiTable)report.GetComponentByName(StiTableName);
table.DataSourceName = DataSourceName;
table.AutoWidthType = StiTableAutoWidthType.LastColumns;
table.ColumnCount = dataTable.Columns.Count;
table.RowCount = 3;
table.HeaderRowsCount = 1;
table.FooterRowsCount = 1;
//table.Width = page.Width;
//table.Height = page.GridSize * 12;
//table.DataSourceName = DataSourceName;
table.CreateCell();
table.TableStyleFX = new StiTable21StyleFX();
table.TableStyle = Stimulsoft.Report.Components.Table.StiTableStyle.Style59;
int indexHeaderCell = 0;
int indexDataCell = dataTable.Columns.Count;
//int indexDataCell = dataTable.Columns.Count;
foreach (DataColumn column in dataView.Table.Columns)
{
// Set text on header
StiTableCell headerCell = table.Components[indexHeaderCell] as StiTableCell;
headerCell.Text.Value = column.Caption;
headerCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
StiTableCell dataCell = table.Components[indexDataCell] as StiTableCell;
dataCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
dataCell.Text.Value = "{" + DataSourceName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(32, 178, 170), 1, StiPenStyle.Dash);
indexHeaderCell++;
indexDataCell++;
}
// Set text on footer
StiTableCell footerCell = table.Components[table.Components.Count - 1] as StiTableCell;
footerCell.Text.Value = "Count - {Count()}";
footerCell.Font = new Font("Arial", 15, FontStyle.Bold);
footerCell.VertAlignment = StiVertAlignment.Center;
footerCell.HorAlignment = StiTextHorAlignment.Center;
}
Thank you.
I'ts been 2 weeks and I even tried other ways like
report.GetComponentByName("Table1");
and still nothing ,
I really need this in short time ,
Will appreiciate your help.
Thank you.
This is a HOTFIX:
private void PrintTableFine(StiReport report ,DataTable dataTable)
{
DataView dataView = new DataView(dataTable);
report.Load(Application.StartupPath + "\\A4 Portrait.mrt");
report.ScriptLanguage = StiReportLanguageType.CSharp;
// Add data to datastore
report.RegData("view", dataView);
// Fill dictionary
report.Dictionary.Synchronize();
StiPage page = report.Pages.Items[0];
// Create Table
StiTable table = new StiTable();
table.Name = "Table1";
table.AutoWidthType = StiTableAutoWidthType.LastColumns;
table.ColumnCount = dataTable.Columns.Count;
table.RowCount = 3;
table.HeaderRowsCount = 1;
table.FooterRowsCount = 1;
table.Width = page.Width;
table.Height = page.GridSize * 12;
table.DataSourceName = "view" + dataView.Table.TableName;
page.Components.Add(table);
table.CreateCell();
table.TableStyleFX = new StiTable21StyleFX();
table.TableStyle = Stimulsoft.Report.Components.Table.StiTableStyle.Style31;
int indexHeaderCell = 0;
int indexDataCell = dataTable.Columns.Count;
foreach (DataColumn column in dataView.Table.Columns)
{
// Set text on header
StiTableCell headerCell = table.Components[indexHeaderCell] as StiTableCell;
headerCell.Text.Value = column.Caption;
headerCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Bold);
headerCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
headerCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(0, 0, 0), 1, StiPenStyle.Dash);
StiTableCell dataCell = table.Components[indexDataCell] as StiTableCell;
dataCell.Text.Value = "{view" + dataView.Table.TableName + "." +
Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Regular);
dataCell.HorAlignment = StiTextHorAlignment.Center;
dataCell.VertAlignment = StiVertAlignment.Center;
dataCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(0, 0, 0), 1, StiPenStyle.Dash);
indexHeaderCell++;
indexDataCell++;
}
// Set text on footer
StiTableCell footerCell = table.Components[table.Components.Count - 1] as StiTableCell;
//footerCell.Text.Value = "Count - {Count()}";
footerCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Regular);
footerCell.VertAlignment = StiVertAlignment.Center;
footerCell.HorAlignment = StiTextHorAlignment.Center;
}
Actually it creates a table.
Please remember , to use it like this :
DataTable dt = new DataTable();
StiReport report = new StiReport();
//Reminder: compiling is after the table
//table:
PrintTableFine(report,dt);
report.Compile();
//adding a variable:
report["Variable"] = "var1ا";
report.Render(false);
report.Show();
Just give it a DataTable and it will create a table with header and footer.
Reminder: the report which your adding this table to SHOULD NOT HAVE A (Sti)TABLE IN IT(in the design).
So I have a gridview with orders filling it. On the side of each row I have set a link button which says "generate invoice". I've defined command name as "GenerateInvoiceCommand" and command argument OrderID so that I can get all the data I need about that order. Now my question is... Is there any way that I can generate a PDF report and once its generated that it automatically starts downloading? Is there any way I can do this without inserting the pdf report first into the database then downloading it?
What other ways are there to generate reports like this?
Any help is appreciated!
Thanks!
I can see there are two ways :
Use Crystal Report to generate PDF, this answer
Write your own code to generate PDFs, my answer
Because you have tagged Crystal Report, you may want to use first but for gaining more control on your report's appearance second option looks better.
you should first use a third party software like crystal-reports or stimulsoft to generate the report's template(myReport.mrt) and then do something like this :
StiReport report = new StiReport();
string path = "~/report/myReport.mrt";
report.Load(Server.MapPath(path));
// register your data to report's template
report.Render();
if (!Directory.Exists(Server.MapPath("~/report/PDF")))
Directory.CreateDirectory(Server.MapPath("~/report/PDF"));
string ReportFileName = Server.MapPath("~/report/PDF/test.pdf");
report.ExportDocument(StiExportFormat.Pdf, ReportFileName);
FileStream file = File.Open(ReportFileName, FileMode.Open);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
file.Close();
Response.WriteFile(ReportFileName);
hope it helps
You can generate a report programmatically using following code in asp.net C#
you should bound your datatable with your data
DataTable dt = GetDataTableFromDGV(AFIs, ArrayTitle, ArrayEnTitle, ArrayOrder, ArrayChecked);
DataView dataView = dt.DefaultView;
report.ScriptLanguage = StiReportLanguageType.CSharp;
report.RegData("view", dataView);
//fill dictionary
report.Dictionary.Synchronize();
StiPage page = report.Pages.Items[0];
if (Landscape)
page.Orientation = StiPageOrientation.Landscape;
else
page.Orientation = StiPageOrientation.Portrait;
//
Double pos = 0;
//Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dataView.Table.Columns.Count, 0.1, true);
Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
int nameIndex = 1;
columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
//create ReportTitleBand
StiReportTitleBand rt = new StiReportTitleBand();
rt.Height = 1.5f;
rt.Name = "ReportTitleBand";
StiText st = new StiText(new RectangleD(0, 0, page.Width, 1f));
st.Text.Value = ReportTitle;
st.HorAlignment = StiTextHorAlignment.Center;
st.Name = "TitleText1";
st.Font = new Font(FontName, 16f);
rt.Components.Add(st);
page.Components.Add(rt);
//create HeaderBand
StiHeaderBand headerBand = new StiHeaderBand();
if (chkRotate)
headerBand.Height = 0.9f;
else
headerBand.Height = 0.5f;
headerBand.Name = "HeaderBand";
page.Components.Add(headerBand);
//create Dataaband
StiDataBand dataBand = new StiDataBand();
dataBand.DataSourceName = "view" + dataView.Table.TableName;
dataBand.Height = 0.5f;
dataBand.Name = "DataBand";
dataBand.CanBreak = true;//Added 11 20 2014
page.Components.Add(dataBand);
//create FooterBand
StiFooterBand footerBand = new StiFooterBand();
footerBand.Height = 0.5f;
footerBand.Name = "FooterBand";
footerBand.Border = new StiBorder(StiBorderSides.All, Color.Black, 1, StiPenStyle.Solid);
footerBand.PrintOnAllPages = true;
page.Components.Add(footerBand);
pos = (page.Width - (columnWidth * Convert.ToDouble(dataView.Table.Columns.Count))) / Convert.ToDouble(2);
for (int i = dataView.Table.Columns.Count - 1; i != -1; i--)
{
DataColumn column = dataView.Table.Columns[i];
//initilized column value
Double headerHeight = 0.5f;
if (chkRotate)
headerHeight = 0.9f;
StiText headerText = new StiText(new RectangleD(pos, 0, columnWidth, headerHeight));
headerText.Text.Value = Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.Caption).Replace("_", " ");//ReplaceUnderLineWithSpace(column.Caption);
if (chkRotate)
headerText.Angle = 90;
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGreen);
headerText.Border.Side = StiBorderSides.All;
headerBand.Components.Add(headerText);
headerText.Font = new Font(FontName, 11.0f);
headerText.WordWrap = true;
headerText.GrowToHeight = true;
//initilized Data Band value
StiText dataText = new StiText(new RectangleD(pos, 0, columnWidth, 0.5f));
dataText.Text.Value = "{view" + dataView.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Border.Side = StiBorderSides.All;
dataText.WordWrap = true;
dataText.GrowToHeight = true;
dataText.Font = new Font(FontName, 11.0f);
//Add highlight
if (true)
{
StiCondition condition = new StiCondition();
condition.BackColor = Color.CornflowerBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1) == 1";
condition.Font = new Font(FontName, 11.0f);
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
}
dataBand.Components.Add(dataText);
pos += columnWidth;
nameIndex++;
}
////footer text
StiText footerText = new StiText(new RectangleD(0, 0, page.Width, 0.5f));
footerText.Text.Value = "صفحه {PageNumber}";
footerText.HorAlignment = StiTextHorAlignment.Center;
footerText.Name = "FooterText";
footerText.Brush = new StiSolidBrush(Color.WhiteSmoke);
footerText.Font = new Font(FontName, 11.0f);
footerBand.Components.Add(footerText);
report.Render(true);
StiWebViewer1.ResetReport();
StiWebViewer1.Report = report;
I am doing a project for class but can't figure out this small pease that has being keeping me up nights. I am creating a page dynamically and it makes a panel for each entry in a database. Now the problem is i use one button for all the buttons on each panel. I need to be able to know what button was pressed so i can send the CarID in a session to another Page.
namespace SportBucks
{
public partial class Auction : System.Web.UI.Page
{
string GCarID = "";
protected void Page_Load(object sender, EventArgs e)
{
bool bWinnerID = false;
bool bWiningBet = false;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if ((string)Session["LoggedIn"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
Service s = new Service();
int Total = s.CarsCount();
for (int loop = Total; loop > 0; loop--)
{
Panel Panel1 = new Panel();
Panel1.ID = "pnl" + loop.ToString();
Panel1.Style["position"] = "absolute";
Panel1.Style["left"] = "155px";
Panel1.Style["top"] = "250px";
Panel1.Style["Height"] = "200px";
Panel1.Style["Width"] = "1000px";
Panel1.BackColor = System.Drawing.Color.Black;
if (loop >= 2)
{
int Top = (250 * (loop - 1));
Panel1.Style["top"] = (250 + Top + 20).ToString() + "px";
}
form1.Controls.Add(Panel1);
string Details = s.LoadCars(loop);
if (Details != null)
{
string CarID = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(CarID + "|", "");
string Man = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Man + "|", "");
string Class = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Class + "|", "");
string Type = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Type + "|", "");
string Description = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Description + "|", "");
string Reserve = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Reserve + "|", "");
string Starting = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Starting + "|", "");
string Begun = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Begun + "|", "");
Begun = Begun.Substring(0, Begun.IndexOf(" "));
string End = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(End + "|", "");
End = End.Substring(0, End.IndexOf(" "));
string WinnerID = "";
string WinningBet = "";
if (Details.Substring(0, 1) == "|")
{
bWinnerID = false;
Details = Details.Substring(1);
}
else
{
WinnerID = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(WinnerID + "|", "");
bWinnerID = true;
}
if (Details.Substring(0, 1) == "|")
{
Details = Details.Substring(1);
bWiningBet = false;
}
else
{
WinningBet = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(WinningBet + "|", "");
bWiningBet = true;
}
string PicUrl = Details.Substring(0, Details.IndexOf("|"));
int Counter = PicUrl.Split(';').Length - 1;
if (Counter >= 1)
{
Image image1 = new Image();
image1.ID = "img" + CarID;
image1.ImageAlign = ImageAlign.AbsMiddle;
image1.Visible = true;
string Pic1 = PicUrl.Substring(0, PicUrl.IndexOf(";"));
image1.ImageUrl = Pic1;
image1.Style["Left"] = "10px";
image1.Style["position"] = "absolute";
image1.Style["top"] = "10px";
image1.Height = 180;
image1.Width = 230;
Panel1.Controls.Add(image1);
}
Label label1 = new Label();
label1.ID = "lblDescription" + CarID;
label1.Text = Description;
label1.ForeColor = System.Drawing.Color.Lime;
label1.BorderStyle = BorderStyle.Groove;
label1.BorderColor = System.Drawing.Color.Violet;
label1.Style["Left"] = "500px";
label1.Style["position"] = "absolute";
label1.Style["top"] = "30px";
Panel1.Controls.Add(label1);
Label label2 = new Label();
label2.ID = "lblBegun" + CarID;
label2.Text = "Auction Start: " + Begun;
label2.ForeColor = System.Drawing.Color.Lime;
label2.Style["Left"] = "270px";
label2.Style["position"] = "absolute";
label2.Style["top"] = "30px";
Panel1.Controls.Add(label2);
Label label3 = new Label();
label3.ID = "lblEnd" + CarID;
label3.Text = "Auction End: " + End;
label3.ForeColor = System.Drawing.Color.Lime;
label3.Style["Left"] = "270px";
label3.Style["position"] = "absolute";
label3.Style["top"] = "50px";
Panel1.Controls.Add(label3);
Label label4 = new Label();
label4.ID = "lblReserve" + CarID;
label4.Text = "Reserve: " + Reserve;
label4.ForeColor = System.Drawing.Color.Lime;
label4.Style["Left"] = "270px";
label4.Style["position"] = "absolute";
label4.Style["top"] = "70px";
Panel1.Controls.Add(label4);
Label label5 = new Label();
label5.ID = "lblMan" + CarID;
label5.Text = "Manufacturer: " + Man;
label5.ForeColor = System.Drawing.Color.Lime;
label5.Style["Left"] = "270px";
label5.Style["position"] = "absolute";
label5.Style["top"] = "90px";
Panel1.Controls.Add(label5);
Label label6 = new Label();
label6.ID = "lblClass" + CarID;
label6.Text = "Class: " + Class;
label6.ForeColor = System.Drawing.Color.Lime;
label6.Style["Left"] = "270px";
label6.Style["position"] = "absolute";
label6.Style["top"] = "110px";
Panel1.Controls.Add(label6);
Label label7 = new Label();
label7.ID = "lblType" + CarID;
label7.Text = "Type: " + Type;
label7.ForeColor = System.Drawing.Color.Lime;
label7.Style["Left"] = "270px";
label7.Style["position"] = "absolute";
label7.Style["top"] = "130px";
Panel1.Controls.Add(label7);
if (bWinnerID == true)
{
Label label8 = new Label();
label8.ID = "lblWinnerID" + CarID;
label8.Text = "WinnerID: " + WinnerID;
label8.ForeColor = System.Drawing.Color.Lime;
label8.Style["Left"] = "270px";
label8.Style["position"] = "absolute";
label8.Style["top"] = "130px";
Panel1.Controls.Add(label8);
}
if (bWiningBet == true)
{
Label label9 = new Label();
label9.ID = "lblWinningBet" + CarID;
label9.Text = "WinningBet R: " + WinningBet;
label9.ForeColor = System.Drawing.Color.Lime;
label9.Style["Left"] = "270px";
label9.Style["position"] = "absolute";
label9.Style["top"] = "130px";
Panel1.Controls.Add(label9);
}
/*int View = s.TimesView(CarID);
Label label10 = new Label();
label10.ID = "lblView" + CarID;
label10.Text = "Times View: " + View;
label10.ForeColor = System.Drawing.Color.Lime;
label10.Style["Left"] = "1000px";
label10.Style["position"] = "absolute";
label10.Style["top"] = "130px";
Panel1.Controls.Add(label10);*/
Button btnView = new Button();
btnView.ID = CarID;
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Click += new EventHandler(this.btnView_Click);
GCarID = CarID;
Panel1.Controls.Add(btnView);
}
}
}
}
void btnView_Click(object sender, EventArgs e)
{
Session["CarID"] = GCarID;
Response.Redirect("View.aspx");
}
}}
Try add a custom html attribute.
//code behind:
Button btnView = new Button();
btnView.ID = CarID;
//here
btnView.Attributes.Add("GCarID", CarID);
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Click += new EventHandler(this.btnView_Click);
//click
void btnView_Click(object sender, EventArgs e)
{
Session["CarID"] = ((Button)sender).Attributes["GCarID"];
Response.Redirect("View.aspx");
}
You need to understand the ASP.NET Life Cycle. Your dynamic controls need to be created in the Page_Init() stage, not the Page_Load().
What is happening is you are creating your controls in the Page_Load and when you click on a button and a post back occurs, your dynamic controls are being destroyed. The viewstate for controls is created after the Page_Init, but before the Page_Load. Therefore, your control's that you create dynamically are not keeping their values (such as the ID).
Check out this page and this page for a basic understanding of what I am talking about.
You want to use Button's Command event with CommandArgument instead of Click event.
CommandArgument is meant for that kind of storing arguments, and retrieves it back on past back.
Button btnView = new Button();
btnView.ID = CarID;
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Command += btnView_Command; // Note: Command event is used instead of Click.
btnView.CommandArgument = CarID; // Note: CarID is stored in CommandArgument.
Panel1.Controls.Add(btnView);
void btnView_Command(object sender, CommandEventArgs e)
{
string carID = e.CommandArgument.ToString();
Session["CarID"] = carID;
Response.Redirect("View.aspx");
}
What's the issue? In your event handler btnView_Click(object sender, EventArgs e), the sender would be the button which got clicked. Just cast sender to Control or Button => (sender as Control) or (sender as Button) and retrieve the carID from the ID property.. (which you set in page load) - btnView.ID = CarID;
This is of course assuming your page viewstate is working fine :) - which can be tricky with dynamically added controls in asp.net
i want to add textboxes dynamically in C# on a button click in a table row. for that i have used the following code.
[1]: http://pastie.org/7702237.
the problem is i am able to adding as many textboxes as I want but they are adding at same location, i mean the table row is not incrementing for every button click instead it is simply replacing the old table row with the new one. Please help me in how to solve this problem.
Thanks in advance
Ganesh
Web-based applications do not maintain state; to this end the state of the table and any variables is not being maintained. With each postback (generated by the button), the table's state reverts to what it was prior to adding a row and then a row is programatically added to it.
In order to achieve your goal, you will need to maintain state somehow. In the following code snippet I am making use of a session:
private List<TableRow> TableRows
{
get
{
if(Session["TableRows"] == null)
Session["TableRows"] = new List<TableRow>();
return (List<TableRow>)Session["TableRows"];
}
}
The following is your code modified to work with the session variable:
TextBox txtE, txtM, txtB;
Button btnAdd, btnDel;
TableRow trow;
TableCell tcell;
foreach(TableRow tr in TableRows)
tblEduDetails.Controls.Add(tr);
int count = TableRows.Count + 1;
txtE = new TextBox();
txtE.ID = "E" + count.ToString();
txtE.Visible = true;
txtE.Text = "E " + count.ToString();
txtE.BorderWidth = 2;
txtE.TextMode = TextBoxMode.SingleLine;
txtE.Height = 30;
txtM = new TextBox();
txtM.ID = "M" + count.ToString();
txtM.Visible = true;
txtM.Text = "M " + count.ToString();
txtM.TextMode = TextBoxMode.SingleLine;
txtM.Height = 30;
txtB = new TextBox();
txtB.ID = "E" + count.ToString();
txtB.Visible = true;
txtB.Text = "B " + count.ToString();
txtB.TextMode = TextBoxMode.SingleLine;
txtB.Height = 30;
btnAdd = new Button();
btnAdd.ID = "A" + count.ToString();
btnDel = new Button();
btnDel.ID = "D" + count.ToString();
trow = new TableRow();
trow.ID = "R" + count.ToString();
trow.BorderWidth = 1;
tcell = new TableCell();
tcell.ID = "E" + count.ToString();
tcell.Controls.Add(txtE);
trow.Controls.Add(tcell);
tcell = new TableCell();
tcell.ID = "B" + count.ToString();
tcell.Controls.Add(txtM);
trow.Controls.Add(tcell);
tcell = new TableCell();
tcell.ID = "M" + count.ToString();
tcell.Controls.Add(txtB);
trow.Controls.Add(tcell);
tblEduDetails.Controls.Add(trow);
TableRows.Add(trow);
In the below code Radio buttons are created dynamically, But I want to create the select index change event of КadioИuttons created dynamically and handle it.....below is the code not firing the event.
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get",sQuestions);
if (ds.Tables.Count > 0 ?? ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = 500;
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = iCnt.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
oRbOptions.Enabled = true;
if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
{
oRbOptions.Checked = true;
}
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
oRbOptions.CheckedChanged += new System.EventHandler(CheckedChanged);
oRbOptions.AutoPostBack = false;
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview.Controls.Add(tblQsn);
}
}
Simple attach an eventhandler for checked change event
oRbOptions.CheckedChanged += (s,e) => {
oRbOptions.AutoPostBack = true;
}
You are setting AutoPostBack is false for radio button .So,
please change false to true
oRbOptions.AutoPostBack = true;