So basically i need to get a row count of Table1. I have created a session which stores people in Table1, but when i create a Session for my int counter i get an error "Cannot modify the result of an unboxing conversion". And also, I would like to ask, how can i add row number into "issaugotasTekstas" (my people) in Table1?
Tank you for suggestions!
namespace ValidWeb
{
public partial class WebForm1 : System.Web.UI.Page
{
private String issaugotasTekstas;
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.Items.Count == 0)
{
DropDownList1.Items.Add("-");
for (int i = 14; i <= 25; i++)
{
DropDownList1.Items.Add(i.ToString());
}
}
issaugotasTekstas = (string)Session["Registruoti"]; // session for added people
RegistruotasAsmuo(issaugotasTekstas);
int sk = DalyviuSk(Table1);
(int)Session["Dalyviu sk"] = sk; // ERROR HERE
}
protected void Button1_Click(object sender, EventArgs e)
{
string selected = "";
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
selected += item.ToString() + " | ";
}
}
issaugotasTekstas = /*row number */ TextBox1.Text + " | " + TextBox2.Text + " | " + TextBox3.Text + " | " + DropDownList1.SelectedValue + " | " + selected;
// how can i add row number for each row?
RegistruotasAsmuo(issaugotasTekstas);
Session["Registruoti"] = issaugotasTekstas;
}
private void RegistruotasAsmuo(string tekstas)
{
TableCell cell = new TableCell();
cell.Text = tekstas;
TableRow row = new TableRow();
row.Cells.Add(cell);
Table1.Rows.Add(row);
}
private int DalyviuSk(Table table)
{
return Table1.Rows.Count;
}
protected void Button2_Click(object sender, EventArgs e)
{
Table1.Rows.Clear();
}
}
}
Related
I am able to add accounts of different types through another form to the list statements which I can then add to the list box lstaccounts. However, when I select an account in my list box and press the view statement button I get that exception on the 'lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);' line... any idea why this could be happening?
public List<IStatement> statements;
private int accountCounter = 0;
private int statementsViewed = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
statements = new List<IStatement>();
}
private void btnView_Click(object sender, EventArgs e)
{
if (lstAccounts.SelectedIndex > -1)
{
lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);
statementsViewed += 1;
lblTotal.Text = statementsViewed.ToString();
}
}
private string ShowStatement(IStatement item)
{
String msg = "Account Number: " + item.AccountNumber + "\n"
+ "Name: " + item.AccountName + "\n" + item.PrintStatement();
return msg;
}
private void btnAddAccount_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
if(form2.ShowDialog() == DialogResult.OK)
{
if (form2.txtValue.Text == "" && form2.txtMinMonthly.Text == "")
{
BankAccount b = form2.GetBankAccount();
statements.Add(b);
}
else if (form2.txtMinMonthly.Text == "")
{
InsurancePolicy i = form2.GetInsurancePolicy();
statements.Add(i);
}
else
{
PlatinumCurrent p = form2.GetPlatinumCurrent();
statements.Add(p);
}
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os.ToString());
accountCounter += 1;
}
}
}
The exact error I'm getting is: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'TelephoneBanking.IStatement'.'
You added it as .ToString() in your btnAddAccount_Click. Try add the item, not the item.ToString().
private void btnAddAccount_Click(object sender, EventArgs e)
{
...
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os); // ###### removed os.ToString() ######
accountCounter += 1;
}
...
I am trying to attempt to perform a calculation on a button click on one asp.net form (invoice.aspx) then pass it to another response (print.aspx) form and insert that value into a label. However when ever I click the submit the value ends up being 0. No errors arise when this happens. Can this be done??
The following code I have is:
print.aspx.cs
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
double subTotal1 = (double)(Session["subTotal1"]);
lblItem1Ttl.Text = subTotal1.ToString();
}
}
invoice.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Session["subTotal1"] = 0.0;
}
public void btnSubmit_Click(object sender, EventArgs e)
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
}
Any guidance would be appreciated
So rather than using the action attribute in the invoice.aspx form. I removed that attribute and put in Server.Transfer("print.aspx", true); to post to the response page on the button click event. I have also added the try - catch functions to stop the exception throwing. So thanks #dee-see because it was the life cycle just had to go a slightly different way to get around it. The full solution is below
invoice.aspx.cs:
public partial class invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Session["subTotal1"] = 0.0;
Session["subTotal2"] = 0.0;
Session["subTotal3"] = 0.0;
}
}
public void btnSubmit_Click(object sender, EventArgs e)
{
try
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
catch
{
txtQty1.Text = "";
txtPrice1.Text = "";
}
try
{
int qty2 = Int32.Parse(txtQty2.Text);
double price2 = double.Parse(txtPrice2.Text);
Session["subTotal2"] = (double)Session["subTotal2"] + (price2 * qty2);
}
catch
{
}
try
{
int qty3 = Int32.Parse(txtQty3.Text);
double price3 = double.Parse(txtPrice3.Text);
Session["subTotal3"] = (double)Session["subTotal3"] + (price3 * qty3);
}
catch
{
txtQty3.Text = "";
txtPrice3.Text = "";
}
Server.Transfer("print.aspx", true);
}
}
print.aspx.cs:
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
lblItem1Ttl.Text += "$" + (double)(Session["subTotal1"]);
lblItem2Ttl.Text += "$" + (double)(Session["subTotal2"]);
lblItem3Ttl.Text += "$" + (double)(Session["subTotal3"]);
double total = ((double)(Session["subTotal1"]) + ((double)(Session["subTotal2"])) + (double)(Session["subTotal3"]));
lblTotalAmount.Text += "$" + total;
}
}
After trying some solutions I can't get it done.
I am reading the access.mdb file and I am populating
the datagridview.
Then I add checkboxcolumn. After it is done you can select some checkboxes and they will be saved in settings. But as I start the prog again the values of the checkboxes are set but they are not drawn. I have tried dataGridView.Refresh(), dataGridView.EndEdit() and so on. Where is my mistake and what I am missing?
public partial class Form1 : Form {
private List<int> listCheckedColumn = new List<int>();
private List<string> listNewNames = new List<string>();
public Form1() {
InitializeComponent();
//Properties.Settings.Default.Reset(); //fürs debugging
if (!Properties.Settings.Default["pathOpenings"].Equals("leer") && !Properties.Settings.Default["pathProfiles"].Equals("leer")) {
loadOutputData();
//update RESULT Tabelle
}
if (!Properties.Settings.Default["naSysID"].Equals("leer")) {
updateListCheckedColumnFromSettings();
updateCheckboxes();
//update die RESULT Tabelle
}
if (!Properties.Settings.Default["newNames"].Equals("leer")) {
//fülle die new name Liste
//fülle die zellen mit infos
//update die RESULT Tabelle
}
}
private void updateCheckboxes() {
foreach (int value in listCheckedColumn) {
int rowIndex = getRowIndexWithValueX(value);
if (Convert.ToInt32(dataGridView3.Rows[rowIndex].Cells["SystemID"].Value) == value) {
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView3.Rows[rowIndex].Cells["Nicht beachten"];
checkbox.Value = checkbox.TrueValue;
MessageBox.Show("Row:" + checkbox.RowIndex + " Column:" + checkbox.ColumnIndex);
}
}
}
...
...
/// <summary>
///
/// </summary>
internal void loadOutputData() {
var connOpenings = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Properties.Settings.Default["pathOpenings"] + ";");
var connProfiles = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Properties.Settings.Default["pathProfiles"] + ";");
...
//
// System aka System Names Table
//
var sysNames = new DataTable();
var adapterSysNames = new OleDbDataAdapter("SELECT SystemID, SystemName FROM Systems;", connProfiles);
adapterSysNames.Fill(sysNames);
dataGridView3.DataSource = sysNames;
dataGridView3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView3.Sort(dataGridView3.Columns[0], ListSortDirection.Ascending);
DataGridViewCheckBoxColumn checkedColumn = new DataGridViewCheckBoxColumn();
checkedColumn.Name = "Nicht beachten";
checkedColumn.FalseValue = false;
checkedColumn.TrueValue = true;
dataGridView3.Columns.Add(checkedColumn);
dataGridView3.CellValueChanged += new DataGridViewCellEventHandler(dataGridView3_CellValueChanged);
dataGridView3.CurrentCellDirtyStateChanged += new System.EventHandler(dataGridView3_CurrentCellDirtyStateChanged);
}
...
private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == dataGridView3.Columns["Nicht beachten"].Index) {
int cellValue = Convert.ToInt32(dataGridView3.Rows[e.RowIndex].Cells["SystemID"].Value);
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView3.Rows[e.RowIndex].Cells["Nicht beachten"];
if (checkbox.Value == checkbox.TrueValue) {
if (!isInList(listCheckedColumn, cellValue)) {
listCheckedColumn.Add(cellValue);
listCheckedColumn.Sort();
Properties.Settings.Default["naSysID"] = makeStringFromIntList();
Properties.Settings.Default.Save();
}
} else {
if (isInList(listCheckedColumn, cellValue)) {
listCheckedColumn.Remove(cellValue);
listCheckedColumn.Sort();
Properties.Settings.Default["naSysID"] = makeStringFromIntList();
Properties.Settings.Default.Save();
}
}
}
foreach (DataGridViewRow row in dataGridView3.Rows) {
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["Nicht beachten"];
if (chk.Value == chk.TrueValue) {
MessageBox.Show("Checked- Row: " + chk.RowIndex + " Column: " + chk.ColumnIndex);
}
}
}
...
private void dataGridView3_CurrentCellDirtyStateChanged(object sender, EventArgs e) {
if (dataGridView3.IsCurrentCellDirty && dataGridView3.CurrentCell.ColumnIndex == dataGridView3.Columns["Nicht beachten"].Index) {
dataGridView3.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
...
...
}
have you tried with dataGridView.Update()? Maybe that works.
I created a webform that allows the user to dynamically add more textboxes. Right now, as the button is clicked to add another field, it postbacks to itself. The controls are added in the Pre_Init. However when the page reconstructs itself the textbox names are different each time so the data is not being retained on each postback.
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
I have tried this solution How can I get data from dynamic generated controls in ASP .NET MVC?
I have one datagrid that I am using to alternate between showing two different data sources. I have a filter working for one of the data sources, but it dosent work for the other one. Basically, one data grid showing the first data source, then I can click a button to switch to the other data source in the same grid but I cannot filter this one.
Here is the code I have for the filter on the first data source that works:
private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>();
private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Combo box selection changed. Re-bind data
string selectedGroup = (string)cmbGroups.SelectedItem;
//Re-bind the grid
dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;
}
private void txtFilterIn_TextChanged(object sender, TextChangedEventArgs e)
{
FilterDataGrid(txtFilterIn.Text, txtFilterOut.Text, _dicPortStatus[cmbGroups.SelectedItem.ToString()]);
}
private void btnFilterInClear_Click(object sender, RoutedEventArgs e)
{
txtFilterIn.Clear();
}
private void txtFilterOut_TextChanged(object sender, TextChangedEventArgs e)
{
FilterDataGrid(txtFilterIn.Text, txtFilterOut.Text, _dicPortStatus[cmbGroups.SelectedItem.ToString()]);
//((CollectionView)dgPortStatus.ItemsSource).Refresh();
}
private void btnFilterOutClear_Click(object sender, RoutedEventArgs e)
{
txtFilterOut.Clear();
}
private void FilterDataGrid(string inText, string outText, DataSet ds)
{
if (ds != null )
{
if (!string.IsNullOrEmpty(inText) || !string.IsNullOrEmpty(outText))
{
foreach (DataTable dt in ds.Tables)
{
StringBuilder sbFilter = new StringBuilder();
foreach (DataColumn dc in dt.Columns)
{
if (dc.DataType == typeof(string))
{
if (!string.IsNullOrEmpty(inText))
{
if (sbFilter.Length > 0)
sbFilter.Append(" OR ");
sbFilter.Append("(");
sbFilter.Append(dc.ColumnName + " LIKE '%" + inText + "%'");
}
if (!string.IsNullOrEmpty(outText))
{
if (sbFilter.Length > 0)
sbFilter.Append(" AND ");
if (string.IsNullOrEmpty(inText))
sbFilter.Append("(");
sbFilter.Append(dc.ColumnName + " NOT LIKE '%" + outText + "%'");
}
sbFilter.Append(")");
}
if (dc.DataType == typeof(Int32) || dc.DataType == typeof(Double))
{
if (!string.IsNullOrEmpty(inText))
{
if (sbFilter.Length > 0)
sbFilter.Append(" OR ");
sbFilter.Append("(");
sbFilter.Append("CONVERT(" + dc.ColumnName + ", System.String)" + " LIKE '%" + inText + "%'");
}
if (!string.IsNullOrEmpty(outText))
{
if (sbFilter.Length > 0)
sbFilter.Append(" AND ");
if (string.IsNullOrEmpty(inText))
sbFilter.Append("(");
sbFilter.Append("CONVERT(" + dc.ColumnName + ", System.String)" + " NOT LIKE '%" + outText + "%'");
}
sbFilter.Append(")");
}
}
dt.DefaultView.RowFilter = sbFilter.ToString();
}
}
else
{
foreach (DataTable dt in ds.Tables)
{
dt.DefaultView.RowFilter = String.Empty;
}
}
}
}
So if it isn't doing what you think it should, what -is- it doing?
Are you getting back a blank datagrid, is it not filtering, what is happening?
Also, have you tried stepping through the code and checking variable values at different stages to see if the problem lies within your back-end code or if it is in how you are interfaced with DataGrid?
i think problem is in this function
dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;
in this function you are setting datacontext , i think you should set DataSource instead.
dgPortStatus.DataSource = _dicPortStatus[selectedGroup].Portstatus.DefaultView;