Why i can not add data into new added column - c#

I am amateur C# developer.Now i'm working on destkop application and work with MS2015 and SQL Management Studio.I have added new column into my database and write what is needed for it in .cs code,but can not add my data into column.It always shows NULL even if it is not empty.Here is my code about saving data:
private void btnSave_Click(object sender, EventArgs e) {
if (txtAmount.Text=="" ||txtBarcode.Text == "" || txtName.Text == "" || txtEntrance.Text == "" || txtExit.Text == "" || txtQuantity.Text == "" || txtStatus.Text == "")
{
SoundPlayer sp = new SoundPlayer(#"C:\Users\Nicat\Downloads\CompError.wav");
sp.Play();
MessageBox.Show("Please fill all gaps!");
}
else
{
model.Amount = txtAmount.Text.Trim();
model.Name = txtName.Text.Trim();
model.Entrance_Time = txtEntrance.Text.Trim();
model.Exit_Time = txtExit.Text.Trim();
model.Status = txtStatus.Text.Trim();
model.Quantity = txtQuantity.Text.Trim();
model.Barcode_No = txtBarcode.Text.Trim();
using (DBEntities db = new DBEntities())
{
if (model.ID == 0)
db.Tables.Add(model);
else
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
Reset();
PopulateDataGridView();
SoundPlayer sp = new SoundPlayer(#"C:\Users\Nicat\Downloads\Button.wav");
sp.Play();
MessageBox.Show("Inventory submitted succesfully!");
}
}

If you add an exception handler, it will tell you what's wrong.
Wrap your code in a try/catch block.
try
{
// your code goes here
}
catch(Exception ex)
{
Debug.Writeln(ex.Message);
}

Related

How can I store only one object into array in WPF?

Why doesn't the below code store one object into the array? I can't find my mistake. If the array has one object already, it should display another message.
Here is the C# code. I guess the XAML code isn't necessary. Perhaps my mistake is with NULL?
TraderInfos[] bossArray = new TraderInfos[1];
public Reset_Register()
{
InitializeComponent();
}
private void CheckPassword(object sender, RoutedEventArgs e)
{
if (bossArray != null)
{
if (SecurtyQuestionMother.Text == securityQ_mother_textbox.Text && SecurityQuestionSchool.Text == securityQ_school_texbox.Text)
{
foreach (var item in bossArray)
{
PasswordApears.Text = $"Your password is: {item.Password}";
}
}
else
{
PasswordApears.Text = "You've not found it";
}
}
else
{
MessageBox.Show("There isnt being any data stored yet");
}
}
private void SafeTheEntries(object sender, RoutedEventArgs e)
{
if (bossArray == null)
{
TraderInfos boss = new TraderInfos()
{
First_Name = first_name_textbox.Text,
Last_Name = last_name_textbox.Text,
Company_Name = company_name_textbox.Text,
Phonenumber = phonenumber_textbox.Text,
Password = passwordText.Text,
SecurityQuestionMother = securityQ_mother_textbox.Text,
SecurityQuestionSchool = securityQ_school_texbox.Text
};
bossArray[0] = boss;
MessageBox.Show($"dear {boss.First_Name}!\nYour data has been saved!");
}
else
{
MessageBox.Show("You can't enter more one entry!");
}
}
Your code creates the array at the top and, because of that, your array will not be null. The bossArray[0] should be equal to null, not bossArray.
So check
if (bossArray[0] != null)
or
if (bossArray[0] == null)

Unable to check all check boxes in a GridView

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

Session variable at master page is null in ASP.NET

In my login page code behind:
After success of DB
protected void btnLogin_Click(object sender, EventArgs e)
{
int intErr = 0;
LoginDetails objLogDetails = new LoginDetails();
objLogDetails.UserName = txtUsername.Value.ToString();
objLogDetails.UserPassword = txtUserpassword.Value.ToString();
if (Request.Form["rdoLogType"] != null)
sType = Request.Form["rdoLogType"].ToString();
else if (Request.Form["rdoLogType"] == null && txtUsername.Value.ToString().ToLower() == "admin")
sType = "3";
else
sType = "0";
try
{
if (Request.Form["rdoLogType"] == null)
{
intErr = 1;
divErrMsg.InnerText = "Please Select Login type.";
divErrMsg.Visible = true;
}
else
{
int intLogId = 0;
ServeAtDoorstepService objService = new ServeAtDoorstepService();
if (sType == "1")
intLogId = objService.LoginCustomer(objLogDetails);
if (sType == "2")
intLogId = objService.LoginVendor(objLogDetails);
if (sType == "3")
intLogId = objService.LoginCustomer(objLogDetails);
if (string.IsNullOrEmpty(intLogId.ToString().Trim()))
{
intErr = 1;
divErrMsg.InnerText = "Invalid Loginname and Password! Please try again.";
divErrMsg.Visible = true;
}
else
{
Session.Abandon();
Session.RemoveAll();
Session.Add("LoginId", intLogId.ToString());
Session.Add("LoginType", sType);
if (chkAgree.Checked == true)
{
HttpCookie cLoginId = new HttpCookie("LoginId", intLogId.ToString().Trim());
HttpCookie cLoginType = new HttpCookie("LoginType", sType);
cLoginId.Expires = DateTime.Now.AddDays(5);
cLoginType.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginId);
Response.Cookies.Add(cLoginType);
HttpCookie cLoginName = new HttpCookie("LoginName", txtUsername.Value.ToString().Trim());
HttpCookie cPassword = new HttpCookie("Password", txtUserpassword.Value.ToString().Trim());
cLoginName.Expires = DateTime.Now.AddDays(5);
cPassword.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginName);
Response.Cookies.Add(cPassword);
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
}
catch (Exception ex)
{
divErrMsg.InnerText = ex.Message.ToString();
intErr = 1;
}
if (intErr == 0 && Session["LoginType"].ToString() == "1")
Response.Redirect("MyCustomerDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "2")
Response.Redirect("MyVendorDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "3")
Response.Redirect("MyAdminDash.aspx");
}
At my master page
this master page is common to all page
protected void Page_Load(object sender, EventArgs e)
{
isShowHideControl = "0";
lblWelcomeMsg.Visible = false;
lblDashboard.Visible = false;
if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "3"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "3"; // Admin
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "2"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "2"; // Vendor
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "1"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "1"; // Customer
}
}
But LoginId AND LoginType are always null.
Please help me to get the session value.
This is most likely due to the event life cycle of master pages/web forms. I'm not entirely certain, but the mast page Load event may be firing after your Click event. See this page for details: http://msdn.microsoft.com/en-us/library/dct97kc3.ASPX
See msdn Session.Abandon
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
so in your sample you abandon session before redirect and on other pages it becomes unavailable. So for resolve try delete this line from your code in login page
Session.Abandon();

Handle PageIndexChanging event

I have a Query that runs when the user submits a search and the gridview is loaded.
I want to page the gridview and would usually have my grid in a LoadGrid(). I have the paging working ok and everything is good until I want to view page 2 of the GridView.
protected void btn_Search_Click(object sender, EventArgs e)
{
// Init()
// -----
pnl_Message.Visible = false;
lbl_message.Text = String.Empty;
// Clear grid of previous results
// ==============================
ResultsGridView.DataSource = null;
ResultsGridView.DataBind();
try
{
using (var db = new dbDataContext())
{
// Check Fields
// ------------
if (txt_CustomerName.Text == string.Empty && txt_CCNo.Text == string.Empty &&
txt_SwiftNo.Text == string.Empty && drp_Provider.SelectedValue == string.Empty)
{
lbl_message.Text += "* Please enter a search term";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
pnl_results.Visible = false;
}
// Search Database
// ---------------
if (lbl_message.Text == String.Empty)
{
var customer = txt_CustomerName.Text.Length > 1 ? txt_CustomerName.Text.Trim() :
"Xcxcx";
//var provider = drp_Provider.SelectedItem.Text.Trim();
var concern = txt_CCNo.Text == "" ? 0 : Convert.ToInt32(txt_CCNo.Text);
var swiftid = txt_SwiftNo.Text == "" ? 0 : Convert.ToInt32(txt_SwiftNo.Text);
// Check which fields populated
// ----------------------------
var result =
from c in db.tbl_Concerns
where (c.ProviderId == Convert.ToInt32(drp_Provider.SelectedValue))
|| (c.person_Fullname.Contains(customer))
|| (c.SwiftId == swiftid)
|| (c.ConcernId == concern)
select new
{
c.ConcernId,
Swift = c.SwiftId,
FullName = c.person_Fullname,
Provider = c.tbl_Provider.provider_Name,
Concern_Detail = c.tbl_RaisedConcern.RaisedConcernText,
DateFrom = c.concern_DateFrom,
DateTo = c.concern_DateTo
};
// If No Results
// -------------
if (!result.Any())
{
lbl_message.Text += "* No results match your search, please try again.";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
}
else
{
// Show Table
// ----------
pnl_results.Visible = true;
ResultsGridView.DataSource = result;
ResultsGridView.DataBind();
// Table Header Names
// ------------------
ResultsGridView.HeaderRow.Cells[0].Text = "Select";
}
}
}
}
catch (SystemException ex)
{
var exceptionUtility = new genericExceptions();
exceptionUtility.genericSystemException(
ex,
Server.MachineName,
Page.TemplateSourceDirectory.Remove(0, 1) + Page.AppRelativeVirtualPath.Remove(0, 1),
ConfigurationManager.AppSettings["emailSupport"],
ConfigurationManager.AppSettings["emailFrom"],
string.Empty);
}
}
My PageIndexChanging event I would usually call the loadGrid() but I do not have that situation. I have tried just adding ResultsGridView.DataBind() but get the error Sequence contains no elements.
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultsGridView.PageIndex = e.NewPageIndex;
** How Can I bind the Grid**
}
Try this..
session["somename"]=result;
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var somename=session["somename"].Tostring();
ResultsGridView.PageIndex = e.NewPageIndex;
ResultsGridview.Datasource=somename;
REsultsGridview.Databind();
}

Chrome/Safari Back button issue

I am making an application in which we may have 5 or 6 steps.
In first step, i will select the report which i need and save&continue..it will get me to second step...like so...
my problem is according to functionality, when i hit on the browser back button i need to go to previous page.
and again when i press it second time it has to go to my home page,
but it is redirecting me to the previous page.
It is working in all browsers except in chrome and safari.
I am inserting my code for reference..please help me to solve this..
protected void Page_Load(object sender, EventArgs e)
{
DisableHistory();
lnkBackBrowse.Style["visibility"] = "hidden";
if (Session["UserId"] != null)
{
if (Convert.ToInt32(Session["UserId"].ToString()) == 0)
{
TopNavigationMenu.Style["visibility"] = "hidden";
NavigationMenu.Style["visibility"] = "hidden";
if (!Request.Url.ToString().Contains("Home") && !Request.Url.ToString().Contains("SaveandLogout"))
Response.Redirect("Home.aspx");
}
else
{
TopNavigationMenu.Items[0].Text = "Welcome :" + Session["UserName"].ToString();
TopNavigationMenu.Style["visibility"] = "visible";
NavigationMenu.Style["visibility"] = "visible";
if (Session["FirstTimeLogged"] != null && Convert.ToBoolean(Session["FirstTimeLogged"]) == true)
{
TopNavigationMenu.Enabled = false;
NavigationMenu.Enabled = false;
if (!Request.Url.ToString().Contains("MyAccount"))
Response.Redirect("Home.aspx");
}
else
{
GenerateLinks(Session["RoleId"].ToString());
TopNavigationMenu.Enabled = true;
NavigationMenu.Enabled = true;
//TopNavigationMenu.Items[1].Text = "Support <img src='Images/bullet_arrow_down.png' alt='down' title='' />";
if (Request.Url.ToString().Contains("Home"))
Response.Redirect("Default.aspx");
if (!IsPostBack)
{
string strPrevPg = "", strCurrPg = "";
if (Request.UrlReferrer != null)
{
strPrevPg = Request.UrlReferrer.AbsolutePath.ToString();
strPrevPg = strPrevPg.Substring(strPrevPg.IndexOf("/", 1) + 1, strPrevPg.Length - (strPrevPg.IndexOf("/", 1) + 1));
strPrevPg += Request.UrlReferrer.Query.ToString();
}
strCurrPg = Request.Url.AbsolutePath.ToString();
strCurrPg = strCurrPg.Substring(strCurrPg.IndexOf("/", 1) + 1, strCurrPg.Length - (strCurrPg.IndexOf("/", 1) + 1));
bool bFlag;
bFlag = Convert.ToBoolean(Session["goBackPg"]);
if (Session["PrevPg"] != null)
{
if (strCurrPg == Session["PrevPg"].ToString())
{
if (bFlag)
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = "Default.aspx";
bFlag = false;
Session["goBackPg"] = bFlag;
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
}
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
bFlag = false;
Session["goBackPg"] = bFlag;
}
}
}
}
}
}
else
{
Response.Redirect("home.aspx");
}
}
Those browsers are showing you cached content when you press the back button.
You can debug and check, your server is not being hit. This Session code will not work.
You could tell the browser not to cache the page. That way if the user wanted to go back, he would have to reload the content.

Categories