Reputation: 107
How I Clear (reset) form fileds after form submit
protected void lb_insert_Click(object sender, EventArgs e)
{
try
{
FormView _f = FormView1;
usercredential uc = UserHandler.GetUserCredential(UserHandler.GetUserNameAD());
int id_spv = int.Parse(uc.usrID); int? code_section = int.Parse(uc.usrSectionId);
if (((CheckBox)_f.Controls[0].FindControl("other_spv")).Checked)
{
id_spv = int.Parse(((HiddenField)_f.Controls[0].FindControl("hid_other_spv_id")).Value);
code_section = int.Parse(dbcontext.tbl_ref_UserHzr
.Where(p => p.code_hzrUser == id_spv)
.Select(r => r.code_section)
.First().ToString());
//code_section = dbcontext.tbl_ref_UserHzr.Where(x => x.code_hzrUser == id_spv).Select(x => x.code_section).SingleOrDefault();
}
#region <insert new hazard report to tbl_hzr_main />
tbl_hzr_main newitem = new tbl_hzr_main();
newitem.code_company = int.Parse(((CustomControls_DdlCompany)_f.Controls[0].FindControl("ddl_company1")).SelectedValue);
newitem.code_empPIC = int.Parse(((HiddenField)_f.Controls[0].FindControl("hid_pic_id")).Value);
newitem.code_hzrUser = id_spv;
newitem.code_incdLocation = int.Parse(((CustomControls_DdlLocation)_f.Controls[0].FindControl("ddl_location1")).SelectedValue);
newitem.code_main_contractor = int.Parse(((CustomControls_DdlCompany)_f.Controls[0].FindControl("ddl_company1")).SelectedMainConValue);
newitem.code_section = code_section;
newitem.code_usrEntry = int.Parse(uc.usrID);
newitem.date_hzrMain = DateTime.Parse(((TextBox)_f.Controls[0].FindControl("TextBox1")).Text);
newitem.desc_hzrMain = ((TextBox)_f.Controls[0].FindControl("TextBox3")).Text;
newitem.dueDate_hzrMain = DateTime.Parse(((TextBox)_f.Controls[0].FindControl("TextBox1")).Text);
newitem.entryDate_hzrMain = DateTime.Now;
newitem.folup_hzrMain = ((TextBox)_f.Controls[0].FindControl("TextBox4")).Text;
newitem.locDetail_hzrMain = ((TextBox)_f.Controls[0].FindControl("txb_loc_detail")).Text;
newitem.PICsign_status = byte.Parse(((RadioButtonList)_f.Controls[0].FindControl("rbl_sign_pic")).SelectedValue);
newitem.stat_hzrMain = byte.Parse(((RadioButtonList)_f.Controls[0].FindControl("RadioButtonList1")).SelectedValue);
dbcontext.tbl_hzr_main.Add(newitem);
dbcontext.SaveChanges();
#endregion
#region <get latest hazard report ID for foreign key />
long id_hazard_report = long.Parse(dbcontext.tbl_hzr_main
.OrderByDescending(o => o.code_hzrMain)
.Select(s => s.code_hzrMain)
.First().ToString());
//long id_hazard_report = dbcontext.tbl_hzr_main.OrderByDescending(p => p.code_hzrMain).Select(x => x.code_hzrMain).SingleOrDefault();
#endregion
#region <insert finding type/criteria />
tbl_hzrCriteria newcrititem = new tbl_hzrCriteria();
//RadioButtonList rbl_crit = (RadioButtonList)_f.Controls[0].FindControl("rbl_finding_type");
//foreach (ListItem rb in rbl_crit.Items)
//{
// if (rb.Selected)
// {
// newcrititem.code_hzrCritItem = int.Parse(rb.Value);
// }
//}
newcrititem.code_hzrCritItem = int.Parse(((RadioButtonList)_f.Controls[0].FindControl("rbl_finding_type")).SelectedValue);
newcrititem.code_hzrMain = id_hazard_report;
dbcontext.tbl_hzrCriteria.Add(newcrititem);
dbcontext.SaveChanges();
#endregion
#region <insert risk level if location kelanis />
if (((CustomControls_DdlLocation)_f.Controls[0].FindControl("ddl_location1")).SelectedText.ToLower().Trim() == "kelanis")
{
TBL_HZR_MAIN_RISKLEVEL newriskitem = new TBL_HZR_MAIN_RISKLEVEL();
newriskitem.code_hzrMain = id_hazard_report;
newriskitem.code_risk_level = int.Parse(((CustomControls_DdlRiskLevel)_f.Controls[0].FindControl("ddl_risklvl1")).SelectedValue);
dbcontext.TBL_HZR_MAIN_RISKLEVEL.Add(newriskitem);
}
#endregion
#region <upload file(s) and insert name to database />
// Get the HttpFileCollection
//if(Page.IsValid)
// {
// //your logic
// }
HttpFileCollection hfc = Request.Files;
if (hfc != null)
{
string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);
string PicDir;
if (Directory.Exists(cekDir)) //check Folder avlalible or not
{
PicDir = cekDir;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
PicDir = cekDir;
}
string fullname;
string filename;
//FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
// string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
string fileExt = Path.GetExtension(hpf.FileName);
if (hpf.ContentLength >0)
{
///full path name to check exist or not
fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
bool ex = File.Exists(fullname);
if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
{
if(hpf.ContentLength > 200000)/*(hpf.ContentLength > 200000)*/
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
continue;
}
if (ex == true)
{
string f = Path.GetFileName(hpf.FileName.Replace(" ", "_"));
string[] a = new string[1];
a = f.Split('.');
filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
}
else
{
filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();
}
///full path name to store in database with new filename
//string[] aa = new string[1];
//filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
fullname = string.Format("{0}\\{1}", PicDir, filename);
hpf.SaveAs(fullname);
InsertHazardDoc(id_hazard_report, filename);
}
else
{
// FileUpload1.Focus();
ClientScript.RegisterStartupScript(Type.GetType("System.String"),"messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
continue;
}
}
//}
}
}
#endregion
//Page.DataBind();
myfb._success("Hazard Report Succesfully Inserted");
//after show notification above I want to clear data or reset
}
catch (Exception ex)
{
myfb._error(ex.ToString());
}
}
Where I write code for the reset after notification myfb._success("Hazard Report Succesfully Inserted");
Upvotes: 2
Views: 2707
Reputation: 1301
To my understanding you want to reset all fields then show notification. you can try this :
protected void lb_insert_Click(object sender, EventArgs e){
//your previous code...
Session["State"] = "success";
Response.Redirect(Request.RawUrl);
}
then in your page_init :
protected void Page_Load(object sender, EventArgs e){
string state= (string)Session["state"];
if(!string.isNullOrEmpty(state)){
//show your notification here
}
Session.remove("state");
}
Upvotes: 0
Reputation: 23937
You can just reload your current pages with Response.Redirect(Request.RawUrl);
This will do a complete Postback and reload the page from scratch. If you haven't set any custom code, that stores your values in some sort of Cache, or Session storage your form should come back clean.
//Update:
If you want to display some sort of success message, you could append a querystring to your Redirect. In my example I have a TextBox, which displays "It worked" and a submit button, that does the redirect:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["success"] == "true")
{
//show success here
txtSuccess.Visible = true;
}
else
{
//set success invisible
txtSuccess.Visible = false;
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
var url = Request.RawUrl;
//check if querystring already present
if (url.IndexOf('?') == -1) {
//create a querystring
Response.Redirect($"{url}?success=true");
}
else
{
//append to existing querystring parameters
Response.Redirect($"{url}&success=true");
}
}
What this does, it appends a success querystring parameter to your url. It does check if a querystring already exists by checking for a ?
character in the url.
Then it builds the url and redirects. In you Page_Load
method you then just check for that querystring. If it is there, you display your success message, if not - you hide it.
Really simple, but it does its job.
Upvotes: 1
Reputation: 125
You can Try this ,
FormId.Datasource=null;
FormId.databind();
Upvotes: 0