I'd like not exceed 30 insertions in my listview - c#

I have a problem doing it for a week I'm working on and I would love to find a solution ... it is a web application in asp.net and c #
I have a related listeview a database which I am inserting the students .. and I'd like not exceed 30 insertions ... the goal is that if I try to enter the 31th student I must be stopped displaying a warning message
I try Sev code which seems to me that here is the nearest that I put in my page load, but unfortunately its not working
if (ListView1.Items.Count>30)
{
ClientScript.RegisterStartupScript(this.GetType(),
"myalert",
"alert('" + "Dsl .. étudiant !!" + "');", true);
}

Note: All you have said in your problem description is "...but unfortunately its not working", so I don't know for sure what the problem is. I'm assuming that you never actually make it inside the if-block.
You mention that the code in your question is in Page_Load. Just to be safe, I would put it in the databound event of your ListView:
ListView1_DataBound(Object sender, EventArgs e)
{
if (ListView1.Items.Count>30)
{
ClientScript.RegisterStartupScript(this.GetType(),
"myalert",
"alert('" + "Dsl .. étudiant !!" + "');", true);
}
}
This way you know that your ListView1.Items.Count is correct and up-to-date.

Related

btnSubmit_Click skipping try and going straight to catch (Exception ex)

I have two near identical forms on the site and only one of them works. On firing button click they're supposed to collect text from checkbox fields and email that information on. One of the forms try is completely ignored and the error message in catch is displayed
Using the working form on the new page still won't work makes me think there may be issues with the page, but deleting the aspx and aspx.cs pages and rewriting them when it may not be that serious is not something I want to do if it's not necessary. I've tried removing 'if (IsPostBack)' and 'if (LiabilityCheckBox.Checked == true)' on the form with issues among other things, but nothing seems to help.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (LiabilityCheckBox.Checked == true)
{
// validate the Captcha to check we're not dealing with a bot
bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
CaptchaCodeTextBox.Text = null; // clear previous user input
if (!isHuman)
{
lblCaptchaError.Visible = true;
lblCaptchaError.Text = "Incorrect Code. Please try again!";
}
else
{
try
{
//some code
lblRegMessage.Text =
("Registration Successful. Thank you for entering."
+ "Please click button below to finalise Payment and Registration.");
// Clear the textbox values
//Show Continue Button.
ContinueButton.Visible = true;
}
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
}
}
else
{
lblMessage.Text = ("You must check the Liability check box to continue");
}
}
}
I am expecting the result of filling out the form to be the mail is sent and a message appears telling the user "Registration Successful. Thank you for entering."
What I am getting is this:
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
As I checked, your code missing some closing brackets. Please check the brackets are properly closed and in the series.

C# - Information in DataGridView column is flickering

I am a beginner programmer developing a C# WinForms solution in VS 2015 Professional for my school.
After I implemented the code below, the information on column 9 of the DataGridView is flickering and causes the fields on my form to gray out. It displays correctly only after I drag and move the form around the screen.
Can you please take a look at my code and see what the problem is? The code does what I want, but I am sure it can be perfected. Thank you. I really appreciate your time and help.
private void alunos_detDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
decimal midtermGrade = Convert.ToInt32(this.alunos_detDataGridView.Rows[e.RowIndex].Cells[3].Value);
decimal finalGrade = Convert.ToInt32(this.alunos_detDataGridView.Rows[e.RowIndex].Cells[4].Value);
decimal oralGrade = Convert.ToInt32(this.alunos_detDataGridView.Rows[e.RowIndex].Cells[5].Value);
this.alunos_detDataGridView.Rows[e.RowIndex].Cells[9].Value = ((midtermGrade + finalGrade + oralGrade) / 3);
if (alunos_detDataGridView.CurrentRow.Cells[0].Value.ToString() != null)
{
if ((midtermGrade + finalGrade + oralGrade / 3) >= 60)
{
this.alunos_detDataGridView.Rows[e.RowIndex].Cells[10].Value = "Aprovado";
}
else
{
this.alunos_detDataGridView.Rows[e.RowIndex].Cells[10].Value = "Reprovado";
}
}
}
catch
{
}
}
I fixed the problem! I replaced the CellFormatting event with the CellEndEdit event and now everything is back to normal! Thank you all for your feedback. :)
I feel like the grid is continually updating and maybe it isn't stopped until you move the form; therefore removing the focus from the grid. I'm not sure without seeing the entire code or application. Try placing a break point in the code above after the form is up and flickering and see if it is being hit again and again.

Pop Up success mesg doesn't work for me

I created a simple e_form with insertion button, I wanna add pop up message if the insertion process succeed, I add it alone and it works but when combining it with my code I got an error.
my code is
protected void ImageButton1_Click(object sender, EventArgs e)
{
// connection stuff...
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text);
cmd.Parameters.AddWithValue("#dob", TextBox5.Text);
cmd.Parameters.AddWithValue("#id_no", TextBox2.Text);
int result;
result=cmd.ExecuteNonQuery();
if result >0
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "<script>data has been added successfully</script>");
con.close();
}
}
I think you need to check few things before executing the SQL query.
i)are your html DOM elements are populated as soon as the page because RegisterStartupScript method places javascript at the bottom of the page just before closing of the element.
ii)is our ExecuteNonQuery returning result.
RegisterStartupScript (type type,string key,string script,bool addtags) is mostly used for scripts that must run on page load but your code must run on image button click,so use below method
int result = 1;
if (result==1)
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"script", "alert('data has been added successfully');", true);
}
This should work..Cheers
The if requires brackets
if(result > 0)
I would also suggest adding a label or alert. The ,true adds the tags
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "alert('data has been added successfully');", true);

ShowModalDialog of javascript is not closing from ASP Code behind and opening a new pop up of same page

i m opening an Webpage(Clock.aspx) from window.showModalDialog of javascript.In the Clock.aspx i have a button and i want that when the user click on that button the Clock.aspx page will be closed. I dont want to use onClientClick() method of javascript as some server side database insertion is going on and after the insertion i want to close this page.
The Code behind of the button is as follows:-
protected void btnStop_Click(object sender, EventArgs e)
{
_nonProduction = new NonProduction();
if (Session["LastNonProdTimeID"] == null)
{
}
else
{
int NonProdTimeEntryID = Convert.ToInt32(Session["LastNonProdTimeID"]);
//Updating the TimeSpent
isTimeSpentUpdated = _nonProduction.UpdateTimeSpentInDB(NonProdTimeEntryID);
if (isTimeSpentUpdated == true)
{
string timespent = Convert.ToString(_nonProduction.GetTimeSpent(NonProdTimeEntryID));
string msg = "Total time consumed in " +HiddenTaskname.Value.ToString()+": " + timespent.ToString() + " Minutes";
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
//ShowPopUpMsg(msg);
}
else
{
}
}
}
Here when i m clicking on the Button one more (Clock.aspx)pop up is appearing and window is not closing. Please help me that how i close the ShowModalDialog from server side code. I m using Script manager in my page also.
Thanks in Advance.
I had added <base target="_self">to the head section of the clock.aspx page and then it works fine for me.
For mine, I have a function in normal javascript that closes the page in the aspx.
In the code behind, if the update is successful, it calls that function.
// this function is to be called by the popup windows to refresh the opener using specific office code, and close self
function allDoneOffice(office)
{
var opener = self.opener;
if (opener.doRefresh) opener.doRefreshWithOfficeCode(office);
window.open('','_self',''); // IE warning hack
self.close();
}
// update the record
bool b = report.SaveModifiedToDB();
if (b)
{
// don't close the page if nothing was updated
ClientScript.RegisterStartupScript(this.GetType(), "load", "<script type=\"text/javascript\">\n" +
"allDoneOffice('" + report.OfficeCode + "');" + "<" + "/script>");
}
else
{
lblResults.Text += " Unable to save modified report to the database.";
}
Use this code below should work in IE
Response.Write("<script language='javascript'> { self.close() }</script>");

How to call window.alert("message"); from C#?

I have my own exception based on some condition and want to raise an alert when control comes in this catch block
catch (ApplicationException ex)
{
//want to call window.alert function here
}
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:
try
{
...
}
catch(ApplicationException ex){
Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}
if you are using ajax in your page that require script manager Page.ClientScript
will not work,
Try this and it would do the work:
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"alertMessage", #"alert('your Message ')", true);
You can use the following extension method from any web page or nested user control:
static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
{
var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
}
}
}
like this:
class YourPage : Page
{
private void YourMethod()
{
try
{
// do stuff
}
catch(Exception ex)
{
this.ShowAlert(ex.Message);
}
}
}
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.
I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?
If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET
Simple use this to show the alert message box in code behind.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Record Saved Sucessfully');", true);
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
You should try this.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);

Categories

Resources