This is a classic sort of question, I suppose, but it seems that most people are interested in having the textbox cause a postback. I'm not. I just want the event to fire when a postback occurs.
I have created a webpart with a custom editorpart. The editorpart renders with a textbox and a button. Clicking the button causes a dialog to open. When the dialog is closed, it sets the value of the textbox via javascript and then does __doPostBack using the ClientID of the editorpart.
The postback happens, but the TextChanged event never fires, and I'm not sure if it's a problem with the way __doPostBack is invoked, or if it's because of the way I'm setting up the event handler, or something else. Here's what I think is the relevant portion of the code from the editorpart:
protected override void CreateChildControls()
{
_txtListUrl = new TextBox();
_txtListUrl.ID = "targetSPList";
_txtListUrl.Style.Add(HtmlTextWriterStyle.Width, "60%");
_txtListUrl.ToolTip = "Select List";
_txtListUrl.CssClass = "ms-input";
_txtListUrl.Attributes.Add("readOnly", "true");
_txtListUrl.Attributes.Add("onChange", "__doPostBack('" + this.ClientID + "', '');");
_txtListUrl.Text = this.ListString;
_btnListPicker = new HtmlInputButton();
_btnListPicker.Style.Add(HtmlTextWriterStyle.Width, "60%");
_btnListPicker.Attributes.Add("Title", "Select List");
_btnListPicker.ID = "browseListsSmtButton";
_btnListPicker.Attributes.Add("onClick", "mso_launchListSmtPicker()");
_btnListPicker.Value = "Select List";
this.AddConfigurationOption("News List", "Choose the list that serves as the data source.",
new Control[] { _txtListUrl, _btnListPicker });
if (this.ShowViewSelection)
{
_txtListUrl.TextChanged += new EventHandler(_txtListUrl_TextChanged);
_ddlViews = new DropDownList();
_ddlViews.ID = "_ddlViews";
this.AddConfigurationOption("View", _ddlViews);
}
}
protected override void OnPreRender(EventArgs e)
{
ScriptLink.Register(this.Page, "PickerTreeDialog.js", true);
string lastSelectedListId = string.Empty;
if (!this.WebId.Equals(Guid.Empty) && !this.ListId.Equals(Guid.Empty))
{
lastSelectedListId = SPHttpUtility.EcmaScriptStringLiteralEncode(
string.Format("SPList:{0}?SPWeb:{1}:", this.ListId.ToString(), this.WebId.ToString()));
}
string script = "\r\n var lastSelectedListSmtPickerId = '" + lastSelectedListId + "';"
+ "\r\n function mso_launchListSmtPicker(){"
+ "\r\n if (!document.getElementById) return;"
+ "\r\n"
+ "\r\n var listTextBox = document.getElementById('" + SPHttpUtility.EcmaScriptStringLiteralEncode(_txtListUrl.ClientID) + "');"
+ "\r\n if (listTextBox == null) return;"
+ "\r\n"
+ "\r\n var serverUrl = '" + SPHttpUtility.EcmaScriptStringLiteralEncode(SPContext.Current.Web.ServerRelativeUrl) + "';"
+ "\r\n"
+ "\r\n var callback = function(results) {"
+ "\r\n if (results == null || results[1] == null || results[2] == null) return;"
+ "\r\n"
+ "\r\n lastSelectedListSmtPickerId = results[0];"
+ "\r\n var listUrl = '';"
+ "\r\n if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';"
+ "\r\n if (results[1].charAt(0) == '/') results[1] = results[1].substring(1);"
+ "\r\n listUrl = listUrl + results[1];"
+ "\r\n if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';"
+ "\r\n if (results[2].charAt(0) == '/') results[2] = results[2].substring(1);"
+ "\r\n listUrl = listUrl + results[2];"
+ "\r\n listTextBox.value = listUrl;"
+ "\r\n __doPostBack('" + this.ClientID + "','');"
+ "\r\n }"
+ "\r\n LaunchPickerTreeDialog('CbqPickerSelectListTitle','CbqPickerSelectListText','websLists','', serverUrl, lastSelectedListSmtPickerId,'','','/_layouts/images/smt_icon.gif','', callback);"
+ "\r\n }";
this.Page.ClientScript.RegisterClientScriptBlock(typeof(ListPickerEditorPart), "mso_launchListSmtPicker", script, true);
if ((!string.IsNullOrEmpty(_txtListUrl.Text) && _ddlViews.Items.Count == 0) || _listSelectionChanged)
{
_ddlViews.Items.Clear();
if (!string.IsNullOrEmpty(_txtListUrl.Text))
{
using (SPWeb web = SPContext.Current.Site.OpenWeb(this.WebId))
{
foreach (SPView view in web.Lists[this.ListId].Views)
{
_ddlViews.Items.Add(new ListItem(view.Title, view.ID.ToString()));
}
}
_ddlViews.Enabled = _ddlViews.Items.Count > 0;
}
else
{
_ddlViews.Enabled = false;
}
}
base.OnPreRender(e);
}
void _txtListUrl_TextChanged(object sender, EventArgs e)
{
this.SetPropertiesFromChosenListString(_txtListUrl.Text);
_listSelectionChanged = true;
}
Any ideas?
Update: I forgot to mention these methods, which are called above:
protected virtual void AddConfigurationOption(string title, Control inputControl)
{
this.AddConfigurationOption(title, null, inputControl);
}
protected virtual void AddConfigurationOption(string title, string description, Control inputControl)
{
this.AddConfigurationOption(title, description, new List<Control>(new Control[] { inputControl }));
}
protected virtual void AddConfigurationOption(string title, string description, IEnumerable<Control> inputControls)
{
HtmlGenericControl divSectionHead = new HtmlGenericControl("div");
divSectionHead.Attributes.Add("class", "UserSectionHead");
this.Controls.Add(divSectionHead);
HtmlGenericControl labTitle = new HtmlGenericControl("label");
labTitle.InnerHtml = HttpUtility.HtmlEncode(title);
divSectionHead.Controls.Add(labTitle);
HtmlGenericControl divUserSectionBody = new HtmlGenericControl("div");
divUserSectionBody.Attributes.Add("class", "UserSectionBody");
this.Controls.Add(divUserSectionBody);
HtmlGenericControl divUserControlGroup = new HtmlGenericControl("div");
divUserControlGroup.Attributes.Add("class", "UserControlGroup");
divUserSectionBody.Controls.Add(divUserControlGroup);
if (!string.IsNullOrEmpty(description))
{
HtmlGenericControl spnDescription = new HtmlGenericControl("div");
spnDescription.InnerHtml = HttpUtility.HtmlEncode(description);
divUserControlGroup.Controls.Add(spnDescription);
}
foreach (Control inputControl in inputControls)
{
divUserControlGroup.Controls.Add(inputControl);
}
this.Controls.Add(divUserControlGroup);
HtmlGenericControl divUserDottedLine = new HtmlGenericControl("div");
divUserDottedLine.Attributes.Add("class", "UserDottedLine");
divUserDottedLine.Style.Add(HtmlTextWriterStyle.Width, "100%");
this.Controls.Add(divUserDottedLine);
}
It can help, if the class declaring the event handler (in your case the editorpart, I guess) implements System.Web.UI.INamingContainer. And do you add _txtListUrl to the Controls collection?
EDIT:
Make sure that the AutoPostBack property of _txtListUrl is set to true (_txtListUrl.AutoPostBack = true).
_txtListUrl.Attributes.Add("onChange" might interfere with the event handler.
TextChanged is invoked only, when the text box looses the focus.
Related
My update button is not functioning. Whenever I want to update any record, it will not works.
Radio button must be checked in order to update any records in a gridview. After the button is checked, the user will click an update button (located above the gridview). then a page will be displayed. the page will display all the information (in a form view) of the user. he/ she will just change any information they want. after that the user should click update button located below. It is like submitting the form again. But the form is not updated. What should i change?
Below is the code for update button:
protected void update_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string datestart_s = (string)(Session["datestart"]);
datestart_s = Convert.ToDateTime(datestart_s).ToString("yyyy-MM-dd");
string leavetype_c = (string)(Session["leavetype"]);
string X = TextBox3.Text;
string substring1 = X;
string substring2 = "";
foreach (string value in X.Split('-'))
if (X.Length > 40)
{
substring1 = X.Substring(0, 40);
if (X.Length == 80)
{
substring2 = X.Substring(39, 40);
}
else
{
int Xlength = X.Length - 40;
substring2 = X.Substring(40, Xlength);
}
}
OdbcConnection connection = null;
OdbcCommand com = null;
string queryString = "UPDATE QMBSTEST.SCEMLV SET LVTYPE='" + leave.SelectedItem.Value + "', LVDTST='" + start.Text + "', LVDTED='" + end.Text + "', LVDAYS='" + TextBox2.Text + "', LVAMPM='" + time.SelectedItem.Value + "', LVTEXT1='" + substring1 + "', LVTEXT2='" + substring2 + "', LVFLAG='" + apply.SelectedItem.Value + "' WHERE LVEMID='" + TB_EMPID.Text.Trim().ToUpper() + "' AND LVDTST='" + datestart_s.Trim() + "' AND LVTYPE='" + leavetype_c.Trim() + "'";
connection = new OdbcConnection(#"Dsn=as400;Uid=FATIN;Pwd=FATIN;");
com = new OdbcCommand(queryString, connection);
connection.Open();
com.ExecuteNonQuery();
connection.Close();
lblMessage.Text = "Form updated!";
lblMessage.ForeColor = System.Drawing.Color.GreenYellow;
}
}
Are you validating that event with any customvalidator?
If yes then replace :
if (Page.IsValid)
With
IF(!IsValild)
return:
and then ur code.....
Because you not doing anything when any of your validation through validation control got failed.
We want to make an STS that outsources the authentication to google.
Following the steps stated in https://developers.google.com/accounts/docs/OAuth2Login?hl=es-ES we have the following code in the Login.aspx generated by the sts web site template in vs2010:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie(GetUserName(Request.QueryString["code"]), false);
Response.Redirect("default.aspx");
}
else
{
//I want to authenticate
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email")
);
}
}
But I get an error beacuse wa is not specified in the QueryString, debugging the samples and the generated template I saw that wa,wtrealm,wctx and wct are the parameters needed so I used the state parameter so they roundtrip and get them back:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie("johannsw", false);
String lQueryStrings = HttpUtility.UrlDecode(Request.QueryString["state"]);
lQueryStrings.Replace('?', '&');
Response.Redirect("default.aspx" + "?" + lQueryStrings);
}
else
{
//I want to authenticate
String lState = String.Empty;
foreach (var key in Request.QueryString.AllKeys)
{
if (String.Equals("wa", key) ||
String.Equals("wtrealm", key) ||
String.Equals("wctx", key) ||
String.Equals("wct", key))
lState += key + "=" + Request.QueryString[key] + "&";
}
lState = lState.Remove(lState.Length - 1);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
"state=" + HttpUtility.UrlEncode(lState)
);
}
}
but now I get an error saying "The HTTP verb POST used to access path '/WebSite1/' is not allowed."
Any hints?
Thanks!
Well finally I made it. Here is how I solved it just in case it helps someone else:
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null && Request.QueryString["error"] != "access_denied")
{
// If I got code and no error then
// ask for access_code so I can get user email
//Here I ask for the access_code.
WebRequest requestLogIn = null;
Stream stream = null;
WebResponse response = null;
StreamReader reader = null;
string sendData = "code=" + Request.QueryString["code"] + "&";
sendData += "client_id=" + ObtenerClientID() + "&";
sendData += "client_secret=" + ObtenerClientSecret() + "&";
sendData += "redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["urlLogin"] + "&"; //TODO: ver si es necesario
sendData += "grant_type=authorization_code";
requestLogIn = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
requestLogIn.Method = "POST";
requestLogIn.ContentType = "application/x-www-form-urlencoded";
byte[] arrayToSend = Encoding.UTF8.GetBytes(sendData);
requestLogIn.ContentLength = arrayToSend.Length;
stream = requestLogIn.GetRequestStream();
stream.Write(arrayToSend, 0, arrayToSend.Length);
stream.Close();
response = requestLogIn.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
string responseValue = reader.ReadToEnd();
reader.Close();
var lJSONResponse = new JavaScriptSerializer().Deserialize<JSONResponseToken>(responseValue);
//Now that I have the access_code ask for the user email so I can match him in my base and load claims.
WebRequest myRequest = WebRequest.Create("https://www.googleapis.com/oauth2/v2/userinfo");
myRequest.Method = "GET";
myRequest.Headers.Add("Authorization", "Bearer " + lJSONResponse.Access_Token);
response = myRequest.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
responseValue = reader.ReadToEnd();
var lUserMail = new JavaScriptSerializer().Deserialize<JSONResponseUserMail>(responseValue);
// User is authenticated
FormsAuthentication.SetAuthCookie(lUserMail.Email, false);
// default.aspx will load claims
Response.Redirect("default.aspx?" + Request.QueryString.ToString());
}
}
}
else
{
//redirect to google for login.
//Save original url in a cookie for later use.
Guid lGuid = Guid.NewGuid();
CreateContextCookie(lGuid.ToString(), this.Request.Url.AbsoluteUri);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=" + ObtenerClientID() + "&" +
//I want to return here again
"redirect_uri=" + HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["urlLogin"]) + "&" +
//Add scope so I can get user mail.
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
//Reference to the cookie so I can get the original url again
"state=" + HttpUtility.UrlEncode(lGuid.ToString())
);
}
}
Default.aspx.cs:
protected void Page_PreRender(object sender, EventArgs e)
{
String lCode = Request.QueryString["code"];
String lSTate = Request.QueryString["state"];
var ctxCookie = this.Request.Cookies[lSTate];
var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(ctxCookie.Value));
//Erase cookie
var contextCookie = new HttpCookie(lSTate)
{
Expires = DateTime.UtcNow.AddDays(-1)
};
//process login request
SecurityTokenService sts =
new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage responseMessage =
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response);
this.Response.Cookies.Add(contextCookie);
}
I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}
the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx
try this EnableViewState="false"
You have to bind the CollectionPager again on your search.
I have a page with a dynamically created command button.
I need to dynamically wire up a click event so I can grab the CommandArgument of the clicked button.
Button b = new Button();
b.ID = "btnTrigger2";
b.CssClass = "hiddenBtn";
b.CommandName = "lbl3";
b.Click += new EventHandler(btnTrigger_Click);
The problem is the last line - I can't wire up an EventHandler this way - I need to use the standard EventArgs instead of CommandEventArgs.
Anyone have any suggestions on getting this to work? There's got to be a way...
EDIT
Figured I'd post the code that finally worked in case anyone else tries to do the same thing.
`string tabLoadedScript = string.Empty;
string postBackScript = string.Empty;
string script = " <script language='javascript' type='text/javascript'>" + System.Environment.NewLine;
script += "function clientActiveTabChanged(sender, args) {" + System.Environment.NewLine;
int i = 0;
foreach(TabPanel tp in tc1.Tabs)
{
Button b = new Button();
b.ID = "btn" + tp.ClientID;
b.CssClass = "hiddenBtn";
b.CommandName = tp.ID;
b.Command += btnTrigger_Click;
this.form1.Controls.Add(b);
AsyncPostBackTrigger trg = new AsyncPostBackTrigger();
trg.ControlID = "btn" + tp.ClientID;
tabLoadedScript += "var isTab" + tp.ClientID + "loaded=$get('" + tp.Controls[0].ClientID + "');" + System.Environment.NewLine;
postBackScript += "if(!isTab" + tp.ClientID + "loaded && sender.get_activeTabIndex() == " + i + ") {" + System.Environment.NewLine;
postBackScript += "__doPostBack('" + b.ClientID + "','');}" + System.Environment.NewLine;
i++;
}
script += tabLoadedScript;
script += postBackScript;
script += "}" + System.Environment.NewLine;
script += "</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "cs", script, false);
protected void btnTrigger_Click(object sender, CommandEventArgs e)
{
System.Threading.Thread.Sleep(2500);
Panel ctrl = (Panel) FindControlRecursive(this, "pnl" + e.CommandName);
ctrl.Visible = true;
}
public static Control FindControlRecursive(Control Root, string Id)
{
if(Root.ID == Id)
return Root;
foreach(Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if(FoundCtl != null)
return FoundCtl;
}
return null;
}
`
You can still access the CommandArgument using the the first argument passed to the click handler.
Something like:
protected void btnTrigger_Click(object sender, EventArgs e)
{
Button btnTrigger = sender as Button;
String commandArgument = btnTrigger.CommandArgument;
.
.
.
.
//Other code....
}
You need to use the Command event instead of the Click event. Also, assuming you're using a recent version of Visual Studio and .Net, you can simply change the event registration from
b.Click += new EventHandler(btnTrigger_Click);
to
b.Command += btnTrigger_Click
The explicit typing of the delegate is redundant and will be inferred by the compiler. You can now change the signature of your event handler to:
protected void btnTrigger_Click(object sender, CommandEventArgs e)
And the code should work as desired.
Unfortunately, the default code snippets in Visual Studio still generate this old-style event listener code.
I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.