I am trying to save info from a Gridview on page load to a List of Strings. I then want to take that info and email it out. I have looked online for info on this, and so far I have found nothing. I don't understand if my implementation of the ViewState is wrong or simple in the wrong place. Please help?
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
messages = (List<string>)ViewState["messages"];
}
if (Page.IsPostBack)
{
changeByVendor();
//mailFunction(messages);
}
if (!IsPostBack)
{
mailFunction(messages);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((GridView1.DataSourceID == "SqlDataSource2" || GridView1.DataSourceID == "SqlDataSource1") && !(e.Row.Cells[11].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[11].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[13].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[13].BackColor = System.Drawing.Color.Yellow;
string thisRow = "";
for (int i = 0; i < e.Row.Cells.Count; i++)
{
thisRow = thisRow + e.Row.Cells[i];
}
messages.Add(thisRow);
}
}
else if (GridView1.DataSourceID == "SqlDataSource4" && !(e.Row.Cells[6].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[6].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[7].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[7].BackColor = System.Drawing.Color.Yellow;
}
}
ViewState["messages"] = messages;
}
}
Let's suppose we have the following example:
List<string> input = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<string> msgs = new List<string>() { "1", "2", "3" };
ViewState["messages"] = msgs;
}
This will certainly store the List of strings in the viewstate. The problem is, that when we trigger the button click event, the Page_Load event will fire BEFORE the Button1_Click event, thus, the viewstate will still be empty. This can be managed by passing the code into the Page_PreRender event, which will fire after the button_click event.
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}
Related
after clicking my value and pressing my OK_button I cant get the Value out of the listView to save it somewhere else. I cant use listView1.FindItemWithText because I don't have a text to search for.. Idk how to look for the clicked value after I pressed the OK_button
//Create dummy data to display
myData = new string[dataListSize];
for (int i = 0; i < dataListSize; i++)
{
myData[i] = String.Format("{0}", i);
}
}
private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
{
e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = new ListViewItem(myData[e.ItemIndex]);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
String MyString = textBox1.Text.ToString();
ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
//Select the item found and scroll it into view.
if (lvi != null)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(lvi.Index);
listView1.EnsureVisible(lvi.Index);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e){ }
private void OK_button_Click(object sender, EventArgs e)
{
try
{
// OK -> Daten übernehmen
int iCount = this.listView1.SelectedIndices.Count;
if (iCount != 1)
{
MessageBox.Show("Value is empty");
return;
}
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
//WriteProtokoll(ex.ToString(), 0);
Close();
}
}
I found out that I can get my value with:
string txt = listView1.FocusedItem.Text;
i have POS system to fastfood, created by c# and sql server.
after the payment process show me window "Order Successfully Paid" after clicking to ok return to form ProductsReceiptPreview again,
i want after payment process go to the form main.
this is my code.......
private void lblPayments_Click(object sender, EventArgs e)
{
if (pnlPayments.Height != lbl.Height)
{
pnlPayments.Height = lbl.Height;
btnDone.Text = "DONE";
lbl.Text = "RECEIPT";
btnDone.Image = Resources.done;
Data.Show();
}
else
{
pnlPayments.Height = 394;
btnDone.Text = "RECEIPT";
lbl.Text = "AMOUNT";
btnDone.Image = Resources.receipt;
Data.Hide();
}
}
private void Touch_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
txtCashReceived.Text += btn.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
if(txtCashReceived.Text.Length >0) txtCashReceived.Text =
txtCashReceived.Text.Remove(txtCashReceived.Text.Length - 1);
}
double totalBill = 0;
private void btnPay_Click(object sender, EventArgs e)
{
if (txtCashReceived.Text.Length > 0 && totalBill <=
Convert.ToInt32(txtCashReceived.Text) && Data.RowCount > 0)
{
int i = 0;
foreach (var rep in ListReports)
{
i++;
var report = new ModelReports();
report.Productname = rep.Productname;
report.TotalSales = rep.TotalSales;
report.TotalTransactions = rep.TotalTransactions;
report.Save();
}
var rpd = new ProductsReceiptPreview(dataReceiptBindingSource,
txtTotal.Text, txtCashReceived.Text, txtChange.Text);
rpd.ShowDialog();
if (i == ListReports.Count)
{
MessageBox.Show("Order Successfully Paid");
}
pnlProducts.Controls.Clear();
pnlCategoryPanel.Visible = false;
dataReceiptBindingSource.Clear();
LoadTables();
btnDone.PerformClick();
}
else
{
MessageBox.Show("Please pay your order.");
txtCashReceived.Text = "0";
}
}
private void btnPay_Click_1(object sender, EventArgs e)
{
if (txtCashReceived.Text.Length > 0 && totalBill <=
Convert.ToInt32(txtCashReceived.Text) && Data.RowCount > 0)
{
int i = 0;
foreach (var rep in ListReports)
{
i++;
var report = new ModelReports();
report.Productname = rep.Productname;
report.TotalSales = rep.TotalSales;
report.TotalTransactions = rep.TotalTransactions;
report.Save();
}
if (i == ListReports.Count)
{
MessageBox.Show("Order Successfully Paid");
txtCashReceived.Text = "0";
}
pnlProducts.Controls.Clear();
pnlCategoryPanel.Visible = false;
dataReceiptBindingSource.Clear();
LoadTables();
btnDone.PerformClick();
}
else
{
MessageBox.Show("Please pay your order.");
}
}
If you call some code from main then it will return to main when the call is finished. In the case of a Form, it's handled on a different thread started from main. The thread will never return back to main in this context. If you are using a click event to do some action and want to call some other code when that happens, then you need to re-design your infrastructure. Look into SOLID development principles and dependency injection.
https://www.codeproject.com/Tips/1033646/SOLID-Principle-with-Csharp-Example
https://simpleinjector.readthedocs.io/en/latest/windowsformsintegration.html
i have been trying to use the ViewState object to store the counter for clicking the ImageButton.For instance if ImageButton1 is click it will store the counter == 1(or increment) in it if another button is clicked the counter will become null.I tried clicking the imagebutton , the counter becomes 1 however when i try to retrieve from the submit button via the if else statement it retrieves nothing and the button cannot work.In addition no error message has been shown.I am developing something like a seat selector for my project.Any help will be greatly appreciated!.Below are the codes
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (ImageButton1.ImageUrl != "~/Images/bed-occupied.png")
{
ImageButton1.ImageUrl = "~/Images/bed-occupied.png";
if (ViewState["Counter"] == null)
{
counterBed1 = 1;
TextBoxClass.Text = counterBed1.ToString();
}
else
{
counterBed1 = (int)ViewState["Counter"] + 1;
}
}
else
{
ImageButton1.ImageUrl = "~/Images/bed-unoccupied.png";
ViewState["Counter"] = null;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ViewState["Counter"] = counterBed1;
// if(ViewState["Counter"] != null)
if(counterBed1 ==1)
{
Panel_ErrorMsg.Visible = true;
lb_ErrorMsg.Text = "Patient Successfully admitted to hospital";
}
}
You are incrementing the value as well as setting a local variable but please note you are never storing the value back in ViewState object.
int counterBed1 = 0;
if (ImageButton1.ImageUrl != "~/Images/bed-occupied.png")
{
ImageButton1.ImageUrl = "~/Images/bed-occupied.png";
if (ViewState["Counter"] == null)
{
counterBed1 = 1;
TextBoxClass.Text = counterBed1.ToString();
ViewState["Counter"] = counterBed1; // Add This
}
else
{
counterBed1 = (int)ViewState["Counter"] + 1;
ViewState["Counter"] = counterBed1; //Add This
}
}
else
{
ImageButton1.ImageUrl = "~/Images/bed-unoccupied.png";
ViewState["Counter"] = null;
}
Also, don't use class variable as it will be re-initialized after every new request, use local variable instead like this in Submit Button handler:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
int counterBed1 = Convert.ToInt32(ViewState["Counter"]);
// if(ViewState["Counter"] != null)
if(counterBed1 ==1)
{
I am new to C#. I need the text of lblBalance to remain as it is when the btnNew is clicked, while it changes according to some calculatios when btnCalc is clicked. Here is my attempt so far.
FIGURED IT OUT, Thanks!
private void btnReset_Click(object sender, EventArgs e)
{
//Reset balance to 0.
balance = 0m;
lblBalance.Text = "";
tbDate.Text = "";
//Call the setupForm procedure.
setupForm();
}
private void setupForm()
{
//Setupform done once to reduce amount of times code must be entered.
//Code to clear these entries and set radio and checkboxes to false.
tbDate.Text = "";
tbAmount.Text = "";
rDeposit.Checked = false;
rWithdrawal.Checked = false;
rFee.Checked = false;
chkBank.Checked = false;
//Return focus to the date textbox
tbDate.Focus();
}
private void btnNew_Click(object sender, EventArgs e)
{
//Clear form, but retain balance when clicked.
setupForm();
}
private void tbDate_TextChanged(object sender, EventArgs e)
{
}
private void lblBalance_Click(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
decimal Amount;
Amount = decimal.Parse(tbAmount.Text);
if ((rDeposit.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance + Amount);
}
else if ((rWithdrawal.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
else if ((rFee.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
if ((rDeposit.Checked == false) && (rWithdrawal.Checked == false) && (rFee.Checked == false))
{
MessageBox.Show("ERROR: You must select Deposit, Withdrawal, or Service Fee.");
}
}
private void rDeposit_CheckedChanged(object sender, EventArgs e)
{
}
}
}
change:
lblBalance.Text += balance.ToString();
to
lblBalance.Text = balance.ToString();
Inside your btnNew_Click event
I have a gridview that is bound on page load and I've implemented insert using the footer row technique.
Now I tried the pagination in the same gridview.
I don't have errors but when changing page in the DDL of footer row I find all values duplicates.
In first page the output in DDL is:
MSG
PAY
BUY
LIS
If changed the page the second output in page number two is:
MSG
PAY
BUY
LIS
MSG
PAY
BUY
LIS
I'd greatly appreciate any suggestions.
Thanks!
I used this lines in RowDataBound:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList Area_DDL = (DropDownList)e.Row.FindControl("Area_DDL");
Area_DDL.DataTextField = "area_name";
Area_DDL.DataValueField = "area";
Area_DDL.DataSource = Area();
Area_DDL.DataBind();
Area_DDL.Items.FindByValue((e.Row.FindControl("Area") as Label).Text).Selected = true;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Area_DDL = (DropDownList)e.Row.FindControl("Area_DDL");
Area_DDL.DataTextField = "area_name";
Area_DDL.DataValueField = "area";
Area_DDL.DataSource = Area();
Area_DDL.DataBind();
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
Change your code like this, I hope it help:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewBind();
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = GridView1.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
GridView1.PageIndex = ddlPages.SelectedIndex;
GridViewBind();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = GridView1.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
GridView1.PageIndex = 0;
break;
case "Prev":
GridView1.PageIndex = intCurIndex - 1;
break;
case "Next":
GridView1.PageIndex = intCurIndex + 1;
break;
case "Last":
GridView1.PageIndex = GridView1.PageCount - 1;
break;
}
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
{
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
}