I am working on a project.I am creating an asp table dynamically and in table cell I am adding link button depending on condition.But while adding the Click event to link button it is giving an error saying-
System.Web.UI.WebControls.LinkButton.OnClick(System.EventArgs)' is inaccessible due to its protection level
Following is my code of making the table
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
setmonthname();
}
makeCalendar();
}
public void makeCalendar()
{
tblcalendar.Rows.Clear();
//for current month
DateTime startingdate = StartDateOfMonth(DateTime.Now.AddMonths(monthclickedno));
DateTime enddate = EndDateOfMonth(DateTime.Now.AddMonths(monthclickedno));
string startingday = startingdate.DayOfWeek.ToString();
int startingdayno = Convert.ToInt32(startingdate.DayOfWeek);
string endday = enddate.DayOfWeek.ToString();//like saturday is 6,stating is from monday with 1 and ending si sunday with 7
int enddayno = Convert.ToInt32(enddate.DayOfWeek);
//for prevoius month
DateTime enddateprevious = (EndDateOfMonth(DateTime.Now.AddMonths(monthclickedno)));
//for next month
DateTime startingdatenext = StartDateOfMonth(DateTime.Now.AddMonths(1));
DateTime dtstart=startingdate.AddDays(-(startingdayno+1));
//sMonthName = "January";
//int iMonthNo = Convert.ToDateTime("01-" + sMonthName + "-2011").Month;
for (int i = 0; i <7;i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 7;j++ )
{
TableCell tc = new TableCell();
clickablecell ctCell = new clickablecell();
//tc.ID = idtc.ToString();
idtc++;
if(i==0)
{
tr.CssClass = "firstrow";
tc.CssClass = "firstrowcell";
if (j == 0)
tc.Text = "Sun";
else if (j == 1)
tc.Text = "Mon";
else if (j == 2)
tc.Text = "Tue";
else if (j == 3)
tc.Text = "Wed";
else if (j == 4)
tc.Text = "Thu";
else if (j == 5)
tc.Text = "Fri";
else if (j == 6)
tc.Text = "Sat";
tr.Cells.Add(tc);
}
else{
tc.CssClass = "othercells";
dtstart=dtstart.AddDays(1);
//if date is single digit like 1,2
if (dtstart.ToString("dd").Substring(0, (dtstart.ToString("dd").Length)-1) == "0")
ctCell.Text = (dtstart.ToString("dd").Substring(1));
else
ctCell.Text = (dtstart.ToString("dd"));
ctCell.Attributes.Add("onmouseover", "defColor=this.style.backgroundColor; this.style.backgroundColor='LightGray';");
ctCell.Attributes.Add("onmouseout", "this.style.backgroundColor=defColor;");
//ctCell.ID = k.ToString();
k++;
ctCell.Click += new clickablecell.ClickEventHandler(textcell_Click);
//check for events in this date
DataTable dtevents = checkEvents(dtstart.ToString("dd-MM-yyyy"));
if (dtevents.Rows.Count != 0)
{
LinkButton lnkevent = new LinkButton();
if (dtevents.Rows.Count == 1)
{
if (dtevents.Rows[0]["eventtype"].ToString() == "Holiday")
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tcholidaytext";
ctCell.CssClass = "tcholidaytext";
}
else if (dtevents.Rows[0]["eventtype"].ToString() == "Event")
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tceventtext";
ctCell.CssClass = "tceventtext";
}
else
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tcimpdaytext";
ctCell.CssClass = "tcimpdaytext";
}
}
else
{
ctCell.CssClass = "tcmixtext";
}
//lnkevent.Attributes.Add("onClick", "test();");
lnkevent.OnClick += new EventHandler(this,test);
ctCell.Controls.Add(lnkevent);
}
tr.Cells.Add(ctCell);
}
tblcalendar.Rows.Add(tr);
}
}
}
public void test(object sender,EventArgs e)
{
Response.Write("helloo");
}
Please help how I can solve this problem
Correct subscription should look like this:
lnkevent.Click += test;
OnClick is a method used internally inside the class to raise the event. On the contrary you should be subscribing to the event itself.
Related
I have a datatable which is bound to GridView datasource as follows.
Overall i want to Multiply 'Quantity' column value with 'Part1 qty' column value until 'column5' cell value is repeating and so on
the result of operation should appear underneath the value as highlighted in red for understanding
My GridView data currently
I want the following output
Required Output
My GridMarkup
My GridMarkup
What I have done so far is
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax=columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult=0;
int counter = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
counter++;
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity= GridView1.Rows[i-1].Cells[1].Text;
var PreviousGLQuantity= GridView1.Rows[i-1].Cells[result].Text;
//var Quantity = dt.Rows[i].ItemArray[1];
//var GLQuantity = dt.Rows[i].ItemArray[Convert.ToInt64(result)].ToString();
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
MultiplicationResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ) + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
GridView1.Rows[i].Cells[j].Text = o.ToString();
GridView1.Rows[i].Cells[j].Text.Replace("\n", "<br/>");
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}
Thanks in advance.
We can use below Answer
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax = columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult = 0;
decimal currentCellResult = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
var defaultvalue = row.Cells[j].Text.ToString();
var defaultvalueArray = defaultvalue.Split(' ');
var originalMultiplicationResult = defaultvalueArray.Count() == 2 ? defaultvalueArray.Last() : "0";
var originalCellValue = defaultvalueArray.Count() == 2 ? defaultvalueArray.First() : row.Cells[j].Text.ToString();
if (originalCellValue == previousRow.Cells[j].Text)
{
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity = GridView1.Rows[i - 1].Cells[1].Text;
var PreviousGLQuantity = GridView1.Rows[i - 1].Cells[result].Text;
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
currentCellResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ);
MultiplicationResult = currentCellResult + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
if (row.Cells[j].RowSpan == 0)
{
//DataTable dt = (DataTable)ViewState["dt"];
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text = previousRow.Cells[j].Text.Split("");
}
else
{
//DataTable dt = (DataTable)ViewState["dt"];
var t = Convert.ToDecimal(originalMultiplicationResult) - Convert.ToDecimal(currentCellResult) + MultiplicationResult;
object o = dt.Rows[i].ItemArray[j] + " " + t.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text.Replace("\n", "<br>");
}
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}
I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database.
I know that for having events fired for dynamically created controls, I have to create this controls in Page_Load() or in Page_Init().
My project has a Master Page, in which I have a 1 second timer which updates a clock. This timer event calls my admin.aspx Page_Load() function, so my method which creates dynamic controls it's called every 1 second - connection to database is made every one second, please look below to my code.
It's a good practice to do that? Can you please propose some ideas?
protected void Page_Load(object sender, EventArgs e)
{
_SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
panelContent.Style.Add("background-color", _SinopticBackgroundColor);
Control c = GetControlThatCausedPostBack(this);
if (c != null)
{
if (c.ID.Equals("btnManageCategory"))
hfPageManage.Value = "category";
else if (c.ID.Equals("btnManageDevices"))
hfPageManage.Value = "device";
}
if (hfPageManage.Value.Equals("category"))
{
cbTreeViewGroup.Visible = false;
UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
}
else if (hfPageManage.Value.Equals("device"))
{
cbTreeViewGroup.Visible = true;
}
else
{
cbTreeViewGroup.Visible = false;
}
if (!Page.IsPostBack)
{
LoadFunctions(); // loads some values from database into datatables
}
else
{
}
}
And here is the functions which creates controls
private void UpdateSinopticCategoryManager(TreeNode node = null)
{
if (node == null)
return;
DataTable categoriiDT = null;
using (var connection = new SqlConnection(Database.ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM categories WHERE CategoryID = #CategoryID";
command.Parameters.Add("CategoryID", node.Value);
SqlDataAdapter ad = new SqlDataAdapter(command);
DataSet ds = new DataSet("CATEGORYPROPERTIES");
connection.Open();
ad.Fill(ds);
// verificam sa avem date
if (ds.Tables.Count <= 0)
return;
if (ds.Tables[0].Rows.Count <= 0)
return;
categoriiDT = ds.Tables[0];
}
}
// generate table
Table table = new Table();
table.Style.Add("position", "relative");
table.Style.Add("top", "20px");
table.Style.Add("margin-left", "20px");
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth = 1;
// header
TableHeaderRow hr = new TableHeaderRow();
for (int i = 0; i < 2; i++)
{
TableHeaderCell hc = new TableHeaderCell();
if (i > 0)
{
hc.Text = "FUNCTION";
//hc.Width = 200;
}
else
{
hc.Width = 100;
}
hr.Cells.Add(hc);
}
table.Rows.Add(hr);
var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
where a.ColumnName.ToLowerInvariant().Contains("input")
select a.ColumnName).ToArray();
if (inputs.Count() <= 0)
return;
//rows input
for (int i = 0; i < inputs.Count(); i++)
{
TableRow tableRow = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
// adaugare 2 dropdownlist
DropDownList categList = new DropDownList();
categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
foreach (DataRow row in functionsCategories.Rows)
{
categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
}
DropDownList funcList = new DropDownList();
int selF = 0, selC = 0;
for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
{
funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
{
selF = fi;
selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
}
}
funcList.SelectedIndex = selF;
categList.SelectedIndex = functionsCategories.Rows.IndexOf(
(from c in functionsCategories.AsEnumerable()
where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
select c).FirstOrDefault());
cell.Controls.Add(categList);
cell.Controls.Add(funcList);
}
else
{
Label label = new Label();
label.Text = "INPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
tableRow.Cells.Add(cell);
}
table.Rows.Add(tableRow);
}
//rows output
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
DropDownList list = new DropDownList();
list.Width = 200;
list.Items.AddRange(GetOutputFunctions());
list.BorderColor = Color.Goldenrod;
cell.Controls.Add(list);
}
else
{
Label label = new Label();
label.Text = "OUTPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
// add table to panel
panelContent.Controls.Add(table);
}
It's about this: DropDownList categList = new DropDownList();
This may get answered more quickly and effectively in codereview https://codereview.stackexchange.com/
The Print Preview controller shows the first page not the 2n or 3rd.. pages.
Show_Page() method displays the all pages without problem in a list view.
The method that I use for changing the pages print preview controller is as below:
What should I change or add for displaying next and previous pages ?
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.Update();
}
label2.Text = (PrevIndex + 1).ToString();
}
private void ShowPage()
{
streamToRead = new StreamReader(fName, Encoding.UTF8);
string line;
int LineNbr = 0;
li.Items.Clear();
LineNbr = File.ReadAllLines(fName).Length;
li.View = View.Details;
int counter = 0;
ListViewItem Lvi = new ListViewItem();
char sep='|';
int ctr_limit=0;
if (PublicVariables.Grup_It == 0)
ctr_limit = 9;
else
ctr_limit = 7;
string[] tmp1 = new string[ctr_limit];
while (counter < LineNbr && (line = streamToRead.ReadLine()) != null)
{
if (PublicVariables.PrintData == 2 && counter < 3)
goto NextLine;
string[] tmp = line.Split(sep);
for (int i = 0; i < ctr_limit; ++i)
{
if (PublicVariables.Grup_It > 0)
tmp1[i] = tmp[i + 1];
else
tmp1[i] = tmp[i];
}
Lvi = new ListViewItem(tmp1);
li.Items.Add(Lvi);
NextLine:
++counter;
}
streamToRead.Close();
}
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.InvalidatePreview();
}
label2.Text = (PrevIndex + 1).ToString();
}
Instead of ppc.Update() I have to write ppc.InvalidatePreview();
That permits to show the next page.
I Want to Display this very large data into DataGridView.
But i don't know how to do that.
My Data in Sql Table
http://s13.postimg.org/5dodas0k7/data_di_tabel.png
I Want The Data is Displayed like this
http://s18.postimg.org/apnrbbxrd/tampilan_data_yg_diinginkan.png
I Can't display the data with SqlDataAdapter, so i use SqlDataReader in my cx Class.
Here's my code:
public partial class frmPartProduction : DevExpress.XtraEditors.XtraForm
{
public frmPartProduction()
{
InitializeComponent();
}
private void frmPartProduction_Load(object sender, EventArgs e)
{
txtTglAwal.EditValue = DateTime.Now;
txtTglAkhir.EditValue = DateTime.Now.AddMonths(1);
addRow();
}
private void addRow()
{
cx.Sql = "select PartNumber,PartName,BeginingStok from Part";
cx.Execr();
while (cx.Read())
{
String str = "";
for (int i = 0; i < 8; i++)
{
if (i == 0) str = "Forecast";
if (i == 1) str = "Stok Condition by Forecast";
if (i == 2) str = "Production";
if (i == 3) str = "Stok Condition by Production";
if (i == 4) str = "Safety Stok";
if (i == 5) str = "Schedjule Receipt";
if (i == 6) str = "Outgoing";
if (i == 7) str = "PO Release";
DG.Rows.Add();
int row = DG.RowCount - 1;
if (i == 0)
DG.Rows[row].Cells[0].Style.ForeColor = Color.Black;
else
DG.Rows[row].Cells[0].Style.ForeColor = Color.White;
DG.Rows[row].Cells[0].Value = cx.getString("PartNumber");
DG.Rows[row].Cells[1].Value = cx.getString("PartName");
DG.Rows[row].Cells[2].Value = str;
DG.Rows[row].Cells[3].Value = cx.getString("BeginingStok");
}
}
}
private void btnView_Click(object sender, EventArgs e)
{
while (DG.ColumnCount > 4)
{
DG.Columns.RemoveAt(4);
}
DateTime tgl_awal = Convert.ToDateTime(txtTglAwal.Text);
DateTime tgl_akhir = Convert.ToDateTime(txtTglAkhir.Text);
while (tgl_awal <= tgl_akhir)
{
if (tgl_awal.ToString("dddd") != "Saturday" && tgl_awal.ToString("dddd") != "Sunday")
{
DG.Columns.Add("", tgl_awal.ToString("dd-MMM-yyyy"));
DG.Columns[DG.ColumnCount - 1].Width = 80;
}
tgl_awal = tgl_awal.AddDays(1);
}
DateTime tgl;
for (int row = 0; row < DG.RowCount; row++)
{
String PartNumber = DG.Rows[row].Cells[0].Value.ToString();
String Description = DG.Rows[row].Cells[2].Value.ToString();
for (int col = 4; col < DG.ColumnCount; col++)
{
tgl = Convert.ToDateTime(DG.Columns[col].HeaderText);
if (Description == "Safety Stok")
{
cx.Sql = "select LimitStok from Part where PartNumber = #PartNumber";
cx.Param("#PartNumber", PartNumber);
cx.Param("#Description", Description);
cx.Param("#tgl", tgl);
cx.Execr();
if (cx.Read())
{
DG.Rows[row].Cells[col].Value = cx.getInt("LimitStok");
}
else
{
DG.Rows[row].Cells[col].Value = 0;
}
}
else
{
cx.Sql = "select qty from PartProduction where PartNumber = #PartNumber and tgl = #tgl and Description = #Description";
cx.Param("#PartNumber", PartNumber);
cx.Param("#Description", Description);
cx.Param("#tgl", tgl);
cx.Execr();
if (cx.Read())
{
DG.Rows[row].Cells[col].Value = cx.getFloat("qty");
}
else
{
DG.Rows[row].Cells[col].Value = 0;
}
}
}
}
}
}
I Initialized the DataGrid Column with addRow() method,
and i add date column in btnView_Click.
how can i display the date, in horizontal display?:-(example,
the table
PartNumber PartName Description Tgl Qty
100 Part X Forecast 01-10-2013 10
100 Part X Forecast 02-10-2013 10
100 Part X Forecast 03-10-2013 10
I Want the datagrid display is like this
DataGrid Display
PartNumber PartName 01-10-2013 02-10-2013 03-10-2013
100 Part X 0 0 2
101 Part Y 0 0 2
102 Part Z 2 0 2
You can use the Following code to bind the Data from database to GridView.
Please change the ConnectionString and SqlQuery asper your requirement.
private void getData()
{
String strCon = "Data Source=(local);Initial Catalog=database;uid=uid;pwd=pwd;Integrated Security=True;";
using (SqlConnection sqlCon = new SqlConnection(strCon))
{
String strCmd = "select PartNumber,PartName,BeginingStok from Part";
using (SqlCommand sqlcommand = new SqlCommand(strCmd, sqlCon))
{
sqlCon.Open();
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlcommand))
{
DataSet ds = new DataSet();
sqlAdapter.Fill(ds);
//DG.DataSource = ds.Tables[0];
foreach (DataRow newrow in ds.Tables[0].Rows)
{
String str = "";
for (int i = 0; i < 8; i++)
{
if (i == 0) str = "Forecast";
if (i == 1) str = "Stok Condition by Forecast";
if (i == 2) str = "Production";
if (i == 3) str = "Stok Condition by Production";
if (i == 4) str = "Safety Stok";
if (i == 5) str = "Schedjule Receipt";
if (i == 6) str = "Outgoing";
if (i == 7) str = "PO Release";
DG.Rows.Add();
int row = DG.RowCount - 1;
if (i == 0)
DG.Rows[row].Cells[0].Style.ForeColor = Color.Black;
else
DG.Rows[row].Cells[0].Style.ForeColor = Color.White;
DG.Rows[row].Cells[0].Value = newrow["PartNumber"];
DG.Rows[row].Cells[1].Value = newrow["PartName"];
DG.Rows[row].Cells[2].Value = str;
DG.Rows[row].Cells[3].Value = newrow["BeginingStok"];
}
}
}
}
}
}
I am trying to fire radiobutton checked changed event on linkbutton click event but instead it goes to the page load and the radiobutton checkedchanged event does not fires.
protected void Page_Load(object sender, EventArgs e)
{
string Query = "select Q101004,Q101005 from Q101 where Q101001<110000013";
DataTable dt = ExecuteDataset(Query).Tables[0];
ViewState["dt"] = dt;
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = "Click Here";
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi";
lnkbtn.ID = "Hi";
PlaceHolder2.Controls.Add(lnkbtn);
for (int i = 0; i < dt.Rows.Count; i++)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m" +i;
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx"+i;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int j = 0; j < options.Length; j++)
{
CbxList.Items.Add(new ListItem(options[j], options[j]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (i ==0)
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
else
lnkbtn.Click += new EventHandler(lnkbtn_Click);
}
}
void lnkbtn_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
lnkbtn = (LinkButton)PlaceHolder2.FindControl("Hi");
string str=((LinkButton)sender).CommandArgument;
//lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m";
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (lnkbtn.CommandName == "Test")
{
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
}
}
}
Your code subscribes to the checked changed but does not invoke it.
If you want to do this, you could call the rb_CheckedChanged() method directly.
hope this helps....its working fine for me.
Just Modify your code with this code and You will be able to achieve your desired output
private void InitPage()
{
string a1, b,a2,b2;
_objSession = (ClsSession)Session["Login"];
ds = _objSession._DataSet;
dtAll = ds.Tables[3];
dr = dtAll.NewRow();
string str2 = (string)ViewState["str1"];
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
b2 = str3[1];
}
else
{
a2 = "a0";
b2 = "b0";
}
str = (string)ViewState["str"];
if (str == null)
{
a1 = "a0";
b = "b";
}
else
{
string[] str1 = str.Split('~');
a1 = str1[0];
b = str1[1];
}
if (str==null)
{
for (int j = 0; j < dtAll.Rows.Count; j++)
{
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = (j + 1).ToString();
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi" + j;
lnkbtn.ID = "Hi" + j;
lnkbtn.ForeColor = Color.Blue;
lnkbtn.Width = 30;
lnkbtn.Font.Bold = true;
lnkbtn.Font.Size = 14;
lnkbtn.Font.Underline = false;
lnkbtn.Click += new EventHandler(lnkbtn_Click);
c.Controls.Add(lnkbtn);
plcHdrLinkButton.Controls.Add(lnkbtn);
}
ViewState["a"] = 0;
}
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
a1 = a2;
}
string resultString = Regex.Match(a1, #"\d+").Value;
int a = int.Parse(resultString);
ViewState["a"] = a;
plcHdrQuestion.Controls.Clear();
rb = new RadioButton();
rb.ID = "m" + a;
rb.AutoPostBack = true;
rb.GroupName = "a";
rb.Text = (a + 1) + "." + " " + dtAll.Rows[a][4].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx" + a;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dtAll.Rows[a][5].ToString().Split('~');
plcHdrQuestion.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
plcHdrQuestion.Controls.Add(rb);
plcHdrQuestion.Controls.Add(CbxList);
rb.CheckedChanged += new EventHandler(lnkbtn_Click);
string st = (string)ViewState["str"];
ViewState["str1"] = st;
ViewState["str"] = null;
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
Boolean _flag=true;
ds = _objSession._DataSet;
dt1 = ds.Tables[3];
dr = dt1.NewRow();
StringBuilder sb=new StringBuilder ();
for (int i = 0; i < dt1.Rows.Count; i++)
{
Cbx = (RadioButton)plcHdrQuestion.FindControl("m" + i);
Cbx1 = (CheckBoxList)plcHdrQuestion.FindControl("Cbx" + i);
if (Cbx != null)
{
if (Cbx.Checked == true)
{
Cbx1.Enabled = true;
_flag = false;
string st1 = (string)ViewState["st"];
string st="c";
if (st1 != null)
st = st1 + "~" + st;
ViewState["st"] = st;
st1 = (string)ViewState["st"];
sb.Append(st);
}
break;
}
}
int count=(sb.ToString().Count());
if (count>2)
{
_flag = true;
}
if ((lnkbtn.CommandName == "Test") && (_flag ==true))
{
for (int j = 0; j < dt1.Rows.Count; j++)
{
lnkbtn = (LinkButton)plcHdrLinkButton.FindControl("Hi" + j);
string str = ((LinkButton)sender).CommandArgument;
lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
ViewState["str"] = str + "~" + lnkbtn.ID;
InitPage();
ViewState["st"] = null;
_flag = false;
break;
}
}
}
}
You need to read up on your ASP.NET Page Life Cycle - http://msdn.microsoft.com/en-us/library/ms178472(VS.100).aspx
Very roughly, the following events get called during page lifecycle.
Init -> Controls are created & wired up with event handlers
Load ViewState/ControlState -> Controls are reset to their previous state from the last round trip (including whether or not they need to fire their events)
Load -> Controls are loaded into the Page's Control Tree
Control Events (Clicks etc...) are executed.
The problem you have is that you are creating your control and wiring it up to fire dynamically in the 4th step there, which is too late in the page lifecycle.
On the next round trip, if someone does interact with that control, and the lifecycle starts over, that control won't exist by the time the page is preparing to execute commands.
You'll need to move the creation of your RadioButton to a much earlier stage in the pages creation. In your updated code, try moving your Page_Load code into the override oninit method instead.