How to display text in message box on different lines? - c#

I want each Total displayed on a different line in the box but at the moment it keep overlapping.
Could someone please show me the way?
private void SummaryButton_Click(object sender, EventArgs e)
{
TotalMoniesTaken = AmountDue + TotalMoniesTaken;
TotalGuests = NumberOfGuests + TotalGuests;
TotalLunchBookings = NumberOfGuests + TotalLunchBookings;
TotalEarlyBookings = NumberOfGuests + TotalEarlyBookings;
TotalLateBookings = NumberOfGuests + TotalLateBookings;
TotalCornerTables = NumberOfGuests + TotalCornerTables;
TotalWaiters = NumberOfGuests + TotalWaiters;
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken +
"Total Number of Bookings = " + TotalGuests +
"Total Lunch Bookings = " + TotalLunchBookings +
"Total Early Bookings = " + TotalEarlyBookings +
"Total Late Bookings = " + TotalLateBookings +
"Total Corner Tables = " + TotalCornerTables +
"Total Waiters = " + TotalWaiters);
}

Displaying this doesn't include a new line:
"Total Monies Taken is €" + TotalMoniesTaken
But this does:
"Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine

Add newlines to each one :
"Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine
"Total Number of Bookings = " + TotalGuests + Environment.NewLine
..etc

There are a few ways that you can do this in C#, firstly you can use newlines in your string
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken +
"\nTotal Number of Bookings = " + TotalGuests +
"\nTotal Lunch Bookings = " + TotalLunchBookings +
"\nTotal Early Bookings = " + TotalEarlyBookings +
"\nTotal Late Bookings = " + TotalLateBookings +
"\nTotal Corner Tables = " + TotalCornerTables +
"\nTotal Waiters = " + TotalWaiters);
Alternatively, you could use Environment.NewLine
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine +
"Total Number of Bookings = " + TotalGuests + Environment.NewLine +
"Total Lunch Bookings = " + TotalLunchBookings + Environment.NewLine +
"Total Early Bookings = " + TotalEarlyBookings + Environment.NewLine +
"Total Late Bookings = " + TotalLateBookings + Environment.NewLine +
"Total Corner Tables = " + TotalCornerTables + Environment.NewLine +
"Total Waiters = " + TotalWaiters);

just use \n at the end of each line
MessageBox.Show("test1 \n test2 \n test3");

You can do two ways:
1st one with \n:
Eg: string msg = "text\nwith two lines";
2nd way with Environment.NewLine:
Eg:string msg = "Text " + Environment.NewLine + "with two lines";

Some of the newer C# features (not tested)
MessageBox.Show(
$#"Total Monies Taken is €{TotalMoniesTaken}
Total Number of Bookings = {TotalGuests}
...");

Related

Make new line of text in the same message that aligns with the very left?

I've been having extreme difficulty with figuring out how to either make a new line of text in the same comment and how to make them line up with each other on the left "wall" of the comment. Maybe the answer is obvious and I just need another set of eyes.
public async void PrintInfo()
{
string info =
"**Stats:**" + "".PadRight(93) +
behindWholeStat[0] + " = " + wholeStats[0] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[0]) + 1)))
+ behindWholeStat[1] + " = " + wholeStats[1] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[1]) + 1)))
+ behindWholeStat[2] + " = " + wholeStats[2] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[2]) + 1)))
+ behindWholeStat[3] + " = " + wholeStats[3] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[3]) + 1)))
+ behindWholeStat[4] + " = " + wholeStats[4] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[4]) + 1)))
+ behindWholeStat[5] + " = " + wholeStats[5] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[5]) + 1)))
+ "**Race:** " + rasr.chossenRace + ", **Subrace:** " + rasr.chossenSubrace + "".PadRight(83 - (rasr.chossenRace.Length + rasr.chossenSubrace.Length))
+ "**Class:** " + casc.chossenClass + ", **Subclass:** " + casc.chossenSubclass + "".PadRight(81 - (casc.chossenClass.Length + casc.chossenSubclass.Length))
+ "**Alignment:** " + chossenAlignment + "".PadRight(85 - (chossenAlignment.Length));
await ReplyAsync(info);
}
Im not quite sure but I think what you are looking for is "\n"
You can insert line breaks in a string with \n
"This will be in first line\nThis will be in second line\nAnd this will be in third"
Output:
This will be in first line
This will be in second line
And this will be in third

Simplify list.add of unknown amount of entries

So I am currently working on a calculator.
One of the requirements is to store the history, which I currently do in a list.
While I have simplified alot of code I can't get my head around simplifying this
if (amountNumbers == 2)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 3)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 4)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 5)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " " + op + " " + userNumbers[4].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
Any idea how I simplify this and make the adding dynamic depending on how many values the user has chosen?
Preferably I want to store the whole string within one index since that is how the history is being displayed.
You can just Join userNumbers values with " " + op + " " separator, then concat calculation at end:
string lastExpression = string.Join(" " + op + " ", userNumbers) + // Join values
" = " + calculation.ToString(); // Concat calculation result
memory.Add(lastExpression);
userNumbers.Clear();
There is no matter which amount of values in userNumbers - they all will be joined with " " + op + " " between each other.
Shorter version with string interpolation:
memory.Add($"{string.Join($" {op} ", userNumbers)} = {calculation}");
userNumbers.Clear();
EDIT.
This is very similar idea with #JonasH's answer, just without converting userNumbers to a collection of strings. Join makes it implicitly at behind.
Easy, loop over userNumbers and build your string, then add it to memory once you're done. Like so:
// Ensure that we don't get an 'IndexOutOfBoundsException'
// By clamping 'amountNumbers' to the length if 'userNumbers' if it's larger
if (amountNumbers > userNumbers.Length)
amountNumbers = userNumbers.Length;
// You could use a normal 'string' and '... += ...' but 'StringBuilder' is more efficient
var sb = new StringBuilder();
for (int i = 0; i < amountNumbers; i++)
sb.Append($"{userNumbers[i].ToString()} ");
// Add the calculation, no space at the start required as the loop adds a trailing space
sb.Append($"= {calculation.ToString()}");
memory.Add(sb.ToString());
Use .Take(amountNumbers) to get at most amountNumbers of user numbers, . And String.Join to combine strings with some separator between each:
var users = userNumbers.Take(amountNumbers).Select(s => s.ToString());
var str = string.Join(" " + op + " ", users);
memory.Add(str + " = " + calculation.ToString());
If you need some special handling for cases, like if amountNumbers< userNumbers.Count or amountNumbers == 1 you need to add that separately. If you know that amountNumbers == userNumbers.Count, then the .Take(...) is not needed.

CSVHelper - ignore blank cells in a row unless they are populated

Using CsvHelper with .NET Core 2.2.
We're parsing a CSV file to then export to a SQL table. There are two different mappings of the CSV columns to the SQL columns, which depend on the first value of each row of the CSV.
This is what we have:
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US2") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
Because the mapping for the Region field specifically is so messy and long, I really want to extract values from those csv fields only if the field is not blank. In many cases, many of those fields will be blank, and the business does not want a ton of concatenated blanks to end up in the database in these cases.
I am wondering if CsvHelper already has a built-in function to achieve this? If not, how would I implement that logic into the above code?
Since the second TaskProdEntity appears to add a 2 each time to the column header, you could have one method that builds your address.
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = GetAddress(csv),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = GetAddress(csv, "2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
private string GetAddress(CsvReader csv, string extension = "")
{
var value = new StringBuilder("Business Mailing Address:");
if (csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension));
}
if (csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension));
}
// The rest of the if statements..............
return value.ToString();
}

DatagridView boolean values update to database

I'm having an issue when I update values from a datagridview row to the database. The issue is that I have designed the table in the DB with certain fields as "bit" data type to store boolean value flags.
When i assign the datatable to the datagridview the system aytomatically displays these certain fields as checkboxes, which suits me just fine.
But when I try to update these values back to the database the boolean values go bananas.....Here is my code...
int fragileChk = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
int inflamChk = (Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
int biologicalChk = (Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
int emergencyChk = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
int usedChk = (Convert.ToBoolean(aRow.Cells[25].Value) ? 1 : 0);
int offerChk = (Convert.ToBoolean(aRow.Cells[27].Value) ? 1 : 0);
string err;
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = '" + aRow.Cells[5].Value.ToString() + "', " +
"PartNumber = '" + aRow.Cells[6].Value.ToString() + "', " +
"SerialNumber = '" + aRow.Cells[7].Value.ToString() + "', " +
"Quanitity = " + aRow.Cells[8].Value + ", " +
"Weight = " + aRow.Cells[10].Value + ", " +
"FragileFlag = " + fragileChk + ", " +
"InflammableFlag =" + inflamChk + ", " +
"BiologicalFlag = " + biologicalChk + ", " +
"EmergencyFlag = " + emergencyChk + ", " +
"SpecialInstructions = '" + aRow.Cells[17].Value.ToString() + "', " +
"ShopCostPrice = " + aRow.Cells[19].Value + ", " +
"RetailPrice1 = " + aRow.Cells[20].Value + ", " +
"RetailPrice2 = " + aRow.Cells[21].Value + ", " +
"WholePrice1 = " + aRow.Cells[22].Value + ", " +
"WholePrice2 = " + aRow.Cells[23].Value + ", " +
"CalculatedPrice = " + aRow.Cells[24].Value + ", " +
"UsedParts = " + usedChk + ", " +
"TimesProcessed = " + aRow.Cells[26].Value + ", " +
"OnOffer = " + offerChk + ", " +
"NotesPerPart = '" + aRow.Cells[28].Value.ToString() + "' " +
"WHERE WarehouseLineID = '" + aRow.Cells[0].Value.ToString() + "'";
myConn.ExecSqlCmd(sqlComm, out err);
any ideas ? (I have declared int values just for diagnostic purposes. Thank you in advance for your help.
Always use parameterised query, Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface.
also you can specify datatype in parameterised query that will helpfull in your case.
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = #ProductDescr " +
"PartNumber = #PartNumber " +
"SerialNumber = #SerialNumber " +
"Quanitity = #Quanitity" +
"Weight = #Weight" +
"FragileFlag = #FragileFlag" +
"InflammableFlag = #InflammableFlag" +
"BiologicalFlag = #BiologicalFlag" +
"EmergencyFlag = #EmergencyFlag" +
"SpecialInstructions = #SpecialInstructions " +
"ShopCostPrice = #ShopCostPrice" +
"RetailPrice1 = #RetailPrice1" +
"RetailPrice2 = #RetailPrice2 " +
"WholePrice1 = #WholePrice1 " +
"WholePrice2 = #WholePrice2 " +
"CalculatedPrice = #CalculatedPrice " +
"UsedParts = #UsedParts " +
"TimesProcessed = #TimesProcessed " +
"OnOffer = #OnOffer " +
"NotesPerPart = #NotesPerPart" +
"WHERE WarehouseLineID = #WarehouseLineID ";
MySqlCommand cmd = new MySqlCommand(sqlComm);
cmd.Parameters.Add("#FragileFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
cmd.Parameters.Add("#InflammableFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
cmd.Parameters.Add("#BiologicalFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
cmd.Parameters.Add("#EmergencyFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
....................................
....................................
....................................
and so on
cmd.ExecuteNonQuery();

ASP.NET c# Fix for the OK event of a custom ConfirmMessagebox inside a function library

We made a function that shows a modalpopupmessage dynamically from c# through javascript, it works fine but we wanted to add a parameter so we can pass a function delegate (or event handler) that would be called if the user presses the OK button. Any suggestions?
Postdata: We don't want the typical "confirm you want to press this button" solution but a function to ask confirmation in any part of the process if necessary. Example: User click on delete item button, in codebehind you check the item has some dependency so show a confirmation message with the mensaje function passing the delegate deleteitemconfirmed(), if the user clicks OK call the delegate...
Function in library:
public static void Mensaje(string mensaje, EventHandler EventoClickLLamar, bool botoncancelar, string cssclass, Color colorfondo)
{
string colorfondox = ColorTranslator.ToHtml(colorfondo);
string idbotonok = EventoClickLLamar == null ? "" : EventoClickLLamar.Method.Name.Replace("_Click", "");
string script =
" function verifyStyle(selector) {" + " \r\n" +
" var rules;" + " \r\n" +
" var haveRule = false;" + " \r\n" +
" " + " \r\n" +
" if (typeof document.styleSheets != \"undefined\") { //is this supported" + " \r\n" +
" var cssSheets = document.styleSheets;" + " \r\n" +
" " + " \r\n" +
" outerloop:" + " \r\n" +
" for (var i = 0; i < cssSheets.length; i++) {" + " \r\n" +
" " + " \r\n" +
" //using IE or FireFox/Standards Compliant" + " \r\n" +
" rules = (typeof cssSheets[i].cssRules != \"undefined\") ? cssSheets[i].cssRules : cssSheets[i].rules;" +
" \r\n" +
" " + " \r\n" +
" for (var j = 0; j < rules.length; j++) {" + " \r\n" +
" if (rules[j].selectorText == selector) {" + " \r\n" +
" haveRule = true;" + " \r\n" +
" break outerloop;" + " \r\n" +
" }" + " \r\n" +
" }//innerloop" + " \r\n" +
" " + " \r\n" +
" }//outer loop" + " \r\n" +
" }//endif" + " \r\n" +
" " + " \r\n" +
" return haveRule;" + " \r\n" +
" }//eof" + " \r\n" +
" function setFading(o, b, e, d, f) {" + " \r\n" +
" var t = setInterval" + " \r\n" +
" (" + " \r\n" +
" function () {" + " \r\n" +
" b = stepFX(b, e, 2);" + " \r\n" +
" setOpacity(o, b / 100);" + " \r\n" +
" if (b == e) {" + " \r\n" +
" if (t) { clearInterval(t); t = null; }" + " \r\n" +
" if (typeof f == 'function') { f(); }" + " \r\n" +
" }" + " \r\n" +
" }" + " \r\n" +
" , d / 50);" + " \r\n" +
" }" + " \r\n" +
" function setOpacity(e, o) {" + " \r\n" +
" // for IE" + " \r\n" +
" e.style.filter = 'alpha(opacity=' + o * 100 + ')';" + " \r\n" +
" // for others" + " \r\n" +
" e.style.opacity = o;" + " \r\n" +
" }" + " \r\n" +
" function stepFX(b, e, s) {" + " \r\n" +
" return b > e ? b - s > e ? b - s : e : b < e ? b + s < e ? b + s : e : b;" + " \r\n" +
" }" + " \r\n" +
" // we may consider adding frames support" + " \r\n" +
" var w = window;" + " \r\n" +
" // shortcut to document" + " \r\n" +
" var d = w.document;" + " \r\n" +
" // canvas, window width and window height" + " \r\n" +
" var r = d.documentElement;" + " \r\n" +
" var ww = w.innerWidth ? w.innerWidth + w.pageXOffset : r.clientWidth + r.scrollLeft;" + " \r\n" +
" var wh = w.innerHeight ? w.innerHeight + w.pageYOffset : r.clientHeight + r.scrollTop;" + " \r\n" +
" // create a block element" + " \r\n" +
" var b = d.createElement('div');" + " \r\n" +
" b.id = 'Message';" + " \r\n" +
" b.className = '" + cssclass + "' || '';" + " \r\n" +
" b.style.cssText = 'top:-9999px;left:-9999px;position:absolute;white-space:nowrap;z-index: 1001;';" +
" \r\n" +
" // classname not passed, set defaults" + " \r\n" +
" if (!verifyStyle(\"." + cssclass + "\")) {" + " \r\n" +
" b.style.margin = '0px 0px';" + " \r\n" +
" b.style.padding = '8px 8px';" + " \r\n" +
" b.style.border = '1px solid #A4BED0';" + " \r\n" +
" b.style.backgroundColor = '#E0ECF1';" + " \r\n" +
" }" + " \r\n" +
" var bx = d.createElement('div');" + " \r\n" +
" bx.style.cssText = 'position: absolute;left:0px;top:0px;width:100%;height:100%;text-align:center;z-index: 1000;background-color: " + //va seguido sin salto
colorfondox + ";opacity:0.5;filter:alpha(opacity=50);'" + " \r\n" +
" d.body.insertBefore(bx, d.body.firstChild);" + " \r\n" +
" d.body.insertBefore(b, d.body.firstChild); " + " \r\n" +
" // write HTML fragment to it " + " \r\n" +
" b.innerHTML = '<table><tr><td>" + mensaje + "</td></tr><tr><td align=\"center\">" +
(string.IsNullOrEmpty(idbotonok)
? "<input type=\"submit\" value=\"Aceptar\" onClick=\"disabled=true;setFading(b, 100, 0, 1000, function () { d.body.removeChild(bx); d.body.removeChild(b); });\" >"
: "<input type=\"submit\" value=\"Aceptar\" onClick=\"__doPostBack(\\'" + idbotonok + "\\',\\'\\')\" id=\"" + idbotonok + "\" >") +
(botoncancelar
? "<input type=\"submit\" value=\"Cancelar\" onClick=\"disabled=true;setFading(b, 100, 0, 1000, function () { d.body.removeChild(bx); d.body.removeChild(b); });\" >"
: "") +
"</td></tr></table>';" + " \r\n" +
" // save width/height before hiding " + " \r\n" +
" var bw = b.offsetWidth;" + " \r\n" +
" var bh = b.offsetHeight;" + " \r\n" +
" // hide, move and then show" + " \r\n" +
" b.style.display = 'none';" + " \r\n" +
" b.style.top = (wh / 2 - bh / 2) + 'px'; //center" + " \r\n" +
" b.style.left = (ww / 2 - bw / 2) + 'px'; //center" + " \r\n" +
" b.style.display = 'block';" + " \r\n";
ScriptManager.RegisterClientScriptBlock((Page)HttpContext.Current.Handler, typeof(Page), "mensaje", script, true);
}
Test Page:
public partial class Test: Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
btnDeleteItem_Click(object sender, EventArgs e)
{
//DB checks
....
....
//After x checks against Database we see the item has some dependency so we ask for confirmation
FunctionsLibrary.Mensaje("This Item has x dependency, are you sure you want to delete it?", btnDeleteItemConfirmed_Click, true, "cssclassx", System.Drawing.Color.Gray);
}
btnDeleteItemConfirmed_Click(object sender, EventArgs e)
{
//delete item definitively, handle dependencies etc...
}
}
Options that we couldnt make work (in case we were on track but something was wrong):
Case 1: (The one implemented in our example code) Using EventHandler + __doPostBack so if you have the buttonid_click defined in your page it would be called on postback. (The event didnt rise...we suppose it was because we didnt add the Ok control back in the page load...which gives us case 2)
Case 2: Save the delegate function passed, register event Page.Load+=GetPostBackControlID(), in the following page load GetPostBackControlID() is called, there we check if the control id clicked is our OK button, if so call the delegate function
So you want to talk to the codebehind from the Javascript dialog? The best solution is to use Ajax. Check out how it is done here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Remember you'll be calling a static method in your codebehind so not all data in the page will be available. You can though for example access the Session object through the HttpCurrent object.
Good luck.
after checking the dependecy set the btnDeleteItem.OnClick as
btnDeleteItem.OnClick +=btnDeleteItemConfirmed_Click
and set btnDeleteItem.OnClientClick
OnClientClick="return confirm('Are you sure you want to delete this item?');"
May This Helps You

Categories