SQL Server : UPDATE not updating database Using C# - c#
I have a webpage that has a web form on it. The form is pre-populated with data from a SQL Server database. The user can go in and edit any of the fields and click the "Save" button on the bottom to update the record in the database. For some reason, the update statement isnt updating the record in the database when I have the form pre-filled with data. If I remove the code pre-filling the form on the page load method the update statement works as it should. When I have the form pre-filled with data in the page load method, the update statement appears to be updating the record with the same data that it already had in it, not the new information the user entered. I am completely lost on how to fix this issue as the form has to have data preloaded in it so the user can edit the form respectively.
Can someone point out an error or some correction that I need to make? I've hit the proverbially brick wall :(
Below you will find the page load method and the save button click event handler.
protected void Page_Load(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
SqlCommand selectCommand = new SqlCommand(selectStatement, connection1);
connection1.Open();
using (SqlDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
UMTextBox.Text = reader["make"].ToString();
UMOTextBox.Text = reader["model"].ToString();
UTTextBox.Text = reader["type"].ToString();
USITextBox.Text = reader["size"].ToString();
USTextBox.Text = reader["serial"].ToString();
UATextBox.Text = reader["arrangement"].ToString();
UCTextBox.Text = reader["class"].ToString();
UDTextBox.Text = reader["discharge"].ToString();
UMSTextBox.Text = reader["make_sheave"].ToString();
USDTextBox.Text = reader["sheave_diameter"].ToString();
USBTextBox.Text = reader["sheave_bore"].ToString();
UBNTextBox.Text = reader["belts"].ToString();
UBSTextBox.Text = reader["belt_size"].ToString();
UFNTextBox.Text = reader["filters"].ToString();
UFSTextBox.Text = reader["filter_size"].ToString();
TCFMDTextBox.Text = reader["unitTotalCFMDesign"].ToString();
TCFMATextBox.Text = reader["unitTotalCFMActual"].ToString();
RACFMDTextBox.Text = reader["unitReturnAirCFMDesign"].ToString();
RACFMATextBox.Text = reader["unitReturnAirCFMActual"].ToString();
OACFMDTextBox.Text = reader["unitOutsideAirCFMDesign"].ToString();
OACFMATextBox.Text = reader["unitOutsideAirCFMActual"].ToString();
EACFMDTextBox.Text = reader["unitExhaustAirCFMDesign"].ToString();
EACFMATextBox.Text = reader["unitExhaustAirCFMActual"].ToString();
FRPMDTextBox.Text = reader["unitFanRPMDesign"].ToString();
FRPMATextBox.Text = reader["unitFanRPMActual"].ToString();
MRPMDTextBox.Text = reader["unitMotorRPMDesign"].ToString();
MRPMATextBox.Text = reader["unitMotorRPMActual"].ToString();
MVDTextBox.Text = reader["unitMotorVoltsDesign"].ToString();
MVATextBox.Text = reader["unitMotorVoltsActual"].ToString();
MADTextBox.Text = reader["unitMotorAmpsDesign"].ToString();
MAATextBox.Text = reader["unitMotorAmpsActual"].ToString();
MMTextBox.Text = reader["motor_make"].ToString();
MFTextBox.Text = reader["motor_frame"].ToString();
MHPTextBox.Text = reader["motor_hp"].ToString();
MRPMTextBox.Text = reader["motor_rpm"].ToString();
MVTextBox.Text = reader["motor_volts"].ToString();
MPHTextBox.Text = reader["motor_phasehz"].ToString();
MFLATextBox.Text = reader["motor_fl_amps"].ToString();
MSFTextBox.Text = reader["motor_sf"].ToString();
MMSTextBox.Text = reader["motor_make_sheave"].ToString();
MSDTextBox.Text = reader["motor_sheave_diameter"].ToString();
MSBTextBox.Text = reader["motor_sheave_bore"].ToString();
MODTextBox.Text = reader["motor_operating_diameter"].ToString();
MSCDTextBox.Text = reader["motor_sheave_center_distance"].ToString();
TSPDTextBox.Text = reader["motorTotalSPDesign"].ToString();
TSPATextBox.Text = reader["motorTotalSPActual"].ToString();
ESPDTextBox.Text = reader["motorEnteringSPDesign"].ToString();
ESPATextBox.Text = reader["motorEnteringSPActual"].ToString();
SSPDTextBox.Text = reader["motorSuctionSPDesign"].ToString();
SSPATextBox.Text = reader["motorSuctionSPActual"].ToString();
DSPDTextBox.Text = reader["motorDischargeSPDesign"].ToString();
DSPATextBox.Text = reader["motorDischargeSPActual"].ToString();
PCSPDTextBox.Text = reader["motorPreheatCoilSPDesign"].ToString();
PCSPATextBox.Text = reader["motorPreheatCoilSPActual"].ToString();
CCSPDTextBox.Text = reader["motorCoolingCoilSPDesign"].ToString();
CCSPATextBox.Text = reader["motorCoolingCoilSPActual"].ToString();
RCSPDTextBox.Text = reader["motorReheatCoilSPDesign"].ToString();
RCSPATextBox.Text = reader["motorReheatCoilSPActual"].ToString();
FSPDTextBox.Text = reader["motorFilterSPDesign"].ToString();
FSPATextBox.Text = reader["motorFilterSPActual"].ToString();
AFSPDTextBox.Text = reader["motorAfterFilterSPDesign"].ToString();
AFSPATextBox.Text = reader["motorAfterFilterSPActual"].ToString();
WSPDTextBox.Text = reader["motorWheelSPDesign"].ToString();
WSPATextBox.Text = reader["motorWheelSPActual"].ToString();
RemarksTextArea.Text = reader["remarks"].ToString();
}
}
connection1.Close();
}
}
And here is the Save button click handler that updates the record in the database.
protected void SaveReportButton_Click(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string unitMake = UMTextBox.Text;
string unitModel = UMOTextBox.Text;
string unitType = UTTextBox.Text;
string unitSize = USITextBox.Text;
string unitSerial = USTextBox.Text;
string unitArrangement = UATextBox.Text;
string unitClass = UCTextBox.Text;
string unitDischarge = UDTextBox.Text;
string unitMS = UMSTextBox.Text;
string unitSD = USDTextBox.Text;
string unitSB = USBTextBox.Text;
string unitBeltNumber = UBNTextBox.Text;
string unitBeltSize = UBSTextBox.Text;
string unitFilterNumber = UFNTextBox.Text;
string unitFilterSize = UFSTextBox.Text;
string unitTotalCFMDesign = TCFMDTextBox.Text;
string unitTotalCFMActual = TCFMATextBox.Text;
string unitReturnAirCFMDesign = RACFMDTextBox.Text;
string unitReturnAirCFMActual = RACFMATextBox.Text;
string unitOutsideAirCFMDesign = OACFMDTextBox.Text;
string unitOutsideAirCFMActual = OACFMATextBox.Text;
string unitExhaustAirCFMDesign = EACFMDTextBox.Text;
string unitExhaustAirCFMActual = EACFMATextBox.Text;
string unitFanRPMDesign = FRPMDTextBox.Text;
string unitFanRPMActual = FRPMATextBox.Text;
string unitMotorRPMDesign = MRPMDTextBox.Text;
string unitMotorRPMActual = MRPMATextBox.Text;
string unitMotorVoltsDesign = MVDTextBox.Text;
string unitMotorVoltsActual = MVATextBox.Text;
string unitMotorAmpsDesign = MADTextBox.Text;
string unitMotorAmpsActual = MAATextBox.Text;
string motorMake = MMTextBox.Text;
string motorFrame = MFTextBox.Text;
string motorHP = MHPTextBox.Text;
string motorRPM = MRPMTextBox.Text;
string motorVolts = MVTextBox.Text;
string motorPhaseHz = MPHTextBox.Text;
string motorFullLoadAmps = MFLATextBox.Text;
string motorSF = MSFTextBox.Text;
string motorMakeSheave = MMSTextBox.Text;
string motorSheaveDiameter = MSDTextBox.Text;
string motorSheaveBore = MSBTextBox.Text;
string motorOperatingDiameter = MODTextBox.Text;
string motorSheaveCDistance = MSCDTextBox.Text;
string motorTotalSPDesign = TSPDTextBox.Text;
string motorTotalSPActual = TSPATextBox.Text;
string motorEnteringSPDesign = ESPDTextBox.Text;
string motorEnteringSPActual = ESPATextBox.Text;
string motorSuctionSPDesign = SSPDTextBox.Text;
string motorSuctionSPActual = SSPATextBox.Text;
string motorDischargeSPDesign = DSPDTextBox.Text;
string motorDischargeSPActual = DSPATextBox.Text;
string motorPreheatCoilSPDesign = PCSPDTextBox.Text;
string motorPreheatCoilSPActual = PCSPATextBox.Text;
string motorCoolingCoilSPDesign = CCSPDTextBox.Text;
string motorCoolingCoilSPActual = CCSPATextBox.Text;
string motorReheatCoilSPDesign = RCSPDTextBox.Text;
string motorReheatCoilSPActual = RCSPATextBox.Text;
string motorFilterSPDesign = FSPDTextBox.Text;
string motorFilterSPActual = FSPATextBox.Text;
string motorAfterFilterSPDesign = AFSPDTextBox.Text;
string motorAfterFilterSPActual = AFSPATextBox.Text;
string motorWheelSPDesign = WSPDTextBox.Text;
string motorWheelSPActual = WSPATextBox.Text;
string remarks = RemarksTextArea.Text;
string updateStatement = #"UPDATE ahu_data SET make=#UNITMAKE, model=#UNITMODEL, type=#UNITTYPE, size=#UNITSIZE, serial=#UNITSERIAL, arrangement=#UNITARRANGEMENT,
class=#UNITCLASS, discharge=#UNITDISCHARGE, make_sheave=#UNITMS, sheave_diameter=#UNITSD, sheave_bore=#UNITSB,
belts=#UNITBELTNUMBER, belt_size=#UNITBELTSIZE, filters=#UNITFILTERNUMBER, filter_size=#UNITBELTSIZE,
unitTotalCFMDesign=#UNITTOTALCFMDESIGN, unitTotalCFMActual=#UNITTOTALCFMACTUAL, unitReturnAirCFMDesign=#UNITRETURNAIRCFMDESIGN,
unitReturnAirCFMActual=#UNITRETURNAIRCFMACTUAL, unitOutsideAirCFMDesign=#UNITOUTSIDEAIRCFMDESIGN,
unitOutsideAirCFMActual=#UNITOUTSIDEAIRCFMACTUAL, unitExhaustAirCFMDesign=#UNITEXHAUSTAIRCFMDESIGN,
unitExhaustAirCFMActual=#UNITEXHAUSTAIRCFMACTUAL, unitFanRPMDesign=#UNITFANRPMDESIGN,
unitFanRPMActual=#UNITFANRPMACTUAL, unitMotorRPMDesign=#UNITMOTORRPMDESIGN, unitMotorRPMActual=#UNITMOTORRPMACTUAL,
unitMotorVoltsDesign=#UNITMOTORVOLTSDESIGN, unitMotorVoltsActual=#UNITMOTORVOLTSACTUAL, unitMotorAmpsDesign=#UNITMOTORAMPSDESIGN,
unitMotorAmpsActual=#UNITMOTORAMPSACTUAL, motor_make=#MOTORMAKE, motor_frame=#MOTORFRAME, motor_hp=#MOTORHP,
motor_rpm=#MOTORRPM, motor_volts=#MOTORVOLTS, motor_phasehz=#MOTORPHASEHZ, motor_fl_amps=#MOTORFULLLOADAMPS,
motor_sf=#MOTORSF, motor_make_sheave=#MOTORMAKESHEAVE, motor_sheave_diameter=#MOTORSHEAVEDIAMETER,
motor_sheave_bore=#MOTORSHEAVEBORE, motor_operating_diameter=#MOTOROPERATINGDIAMETER, motor_sheave_center_distance=#MOTORSHEAVECDISTANCE,
motorTotalSPDesign=#MOTORTOTALSPDESIGN, motorTotalSPActual=#MOTORTOTALSPACTUAL, motorEnteringSPDesign=#MOTORENTERINGSPDESIGN,
motorEnteringSPActual=#MOTORENTERINGSPACTUAL, motorSuctionSPDesign=#MOTORSUCTIONSPDESIGN, motorSuctionSPActual=#MOTORSUCTIONSPACTUAL,
motorDischargeSPDesign=#MOTORDISCHARGESPDESIGN, motorDischargeSPActual=#MOTORDISCHARGESPACTUAL, motorPreheatCoilSPDesign=#MOTORPREHEATCOILSPDESIGN,
motorPreheatCoilSPActual=#MOTORPREHEATCOILSPACTUAL, motorCoolingCoilSPDesign=#MOTORCOOLINGCOILSPDESIGN, motorCoolingCoilSPActual=#MOTORCOOLINGCOILSPACTUAL,
motorReheatCoilSPDesign=#MOTORREHEATCOILSPDESIGN, motorReheatCoilSPActual=#MOTORREHEATCOILSPACTUAL, motorFilterSPDesign=#MOTORFILTERSPDESIGN,
motorFilterSPActual=#MOTORFILTERSPACTUAL, motorAfterFilterSPDesign=#MOTORAFTERFILTERSPDESIGN, motorAfterFilterSPActual=#MOTORAFTERFILTERSPACTUAL,
motorWheelSPDesign=#MOTORWHEELSPDESIGN, motorWheelSPActual=#MOTORWHEELSPACTUAL, remarks=#REMARKS WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
connection1.Open();
using (SqlCommand updateCommand = new SqlCommand(updateStatement, connection1))
{
updateCommand.Parameters.AddWithValue("#UNITMAKE", unitMake);
updateCommand.Parameters.AddWithValue("#UNITMODEL", unitModel);
updateCommand.Parameters.AddWithValue("#UNITTYPE", unitType);
updateCommand.Parameters.AddWithValue("#UNITSIZE", unitSize);
updateCommand.Parameters.AddWithValue("#UNITSERIAL", unitSerial);
updateCommand.Parameters.AddWithValue("#UNITARRANGEMENT", unitArrangement);
updateCommand.Parameters.AddWithValue("#UNITCLASS", unitClass);
updateCommand.Parameters.AddWithValue("#UNITDISCHARGE", unitDischarge);
updateCommand.Parameters.AddWithValue("#UNITMS", unitMS);
updateCommand.Parameters.AddWithValue("#UNITSD", unitSD);
updateCommand.Parameters.AddWithValue("#UNITSB", unitSB);
updateCommand.Parameters.AddWithValue("#UNITBELTNUMBER", unitBeltNumber);
updateCommand.Parameters.AddWithValue("#UNITBELTSIZE", unitBeltSize);
updateCommand.Parameters.AddWithValue("#UNITFILTERNUMBER", unitFilterNumber);
updateCommand.Parameters.AddWithValue("#UNITFILTERSIZE", unitFilterSize);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMDESIGN", unitTotalCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMACTUAL", unitTotalCFMActual);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMDESIGN", unitReturnAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMACTUAL", unitReturnAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMDESIGN", unitOutsideAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMACTUAL", unitOutsideAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMDESIGN", unitExhaustAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMACTUAL", unitExhaustAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITFANRPMDESIGN", unitFanRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITFANRPMACTUAL", unitFanRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMDESIGN", unitMotorRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMACTUAL", unitMotorRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSDESIGN", unitMotorVoltsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSACTUAL", unitMotorVoltsActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSDESIGN", unitMotorAmpsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSACTUAL", unitMotorAmpsActual);
updateCommand.Parameters.AddWithValue("#MOTORMAKE", motorMake);
updateCommand.Parameters.AddWithValue("#MOTORFRAME", motorFrame);
updateCommand.Parameters.AddWithValue("#MOTORHP", motorHP);
updateCommand.Parameters.AddWithValue("#MOTORRPM", motorRPM);
updateCommand.Parameters.AddWithValue("#MOTORVOLTS", motorVolts);
updateCommand.Parameters.AddWithValue("#MOTORPHASEHZ", motorPhaseHz);
updateCommand.Parameters.AddWithValue("#MOTORFULLLOADAMPS", motorFullLoadAmps);
updateCommand.Parameters.AddWithValue("#MOTORSF", motorSF);
updateCommand.Parameters.AddWithValue("#MOTORMAKESHEAVE", motorMakeSheave);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEDIAMETER", motorSheaveDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEBORE", motorSheaveBore);
updateCommand.Parameters.AddWithValue("#MOTOROPERATINGDIAMETER", motorOperatingDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVECDISTANCE", motorSheaveCDistance);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPDESIGN", motorTotalSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPACTUAL", motorTotalSPActual);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPDESIGN", motorEnteringSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPACTUAL", motorEnteringSPActual);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPDESIGN", motorSuctionSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPACTUAL", motorSuctionSPActual);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPDESIGN", motorDischargeSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPACTUAL", motorDischargeSPActual);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPDESIGN", motorPreheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPACTUAL", motorPreheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPDESIGN", motorCoolingCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPACTUAL", motorCoolingCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPDESIGN", motorReheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPACTUAL", motorReheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPDESIGN", motorFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPACTUAL", motorFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPDESIGN", motorAfterFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPACTUAL", motorAfterFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPDESIGN", motorWheelSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPACTUAL", motorWheelSPActual);
updateCommand.Parameters.AddWithValue("#REMARKS", remarks);
updateCommand.ExecuteNonQuery();
}
connection1.Close();
}
}
ASP.NET page lifecycle causes this situation if you don't protect the Page_Load from reexecuting the code that fill your textboxes.
if (!IsPostBack)
{
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
.... rest of code that pre-fill your fields
Page.IsPostBack is a boolean property of the Page that informs your code if the page is called for the first time or if it is called as a consequence of some event that need to be processed server-side.
In the latter case you should not execute again the code that fills your textboxes otherwise, when the flow reaches your button code, you will find the textboxes with the original values instead of the modified ones because the Page_Load has resetted everything.
And do not forget the comment above about parameterizing your first query. You have already done the biggest part parameterizing the UPDATE, just one parameter remains and it is complete.
The update is working just fine, the problem is that it's using the same data that's already in the table, so it won't change anything.
When you click the save button the page does a postback to run the code on the server. First the Page_Load event runs and loads the original data that will replace the data that you entered in the form. Then the SaveReportButton_Click event runs that updates the record.
To keep the Page_Load event handler from replacing the data in the form, you should use the isPostBack property to check if the page is loaded due to a postback:
if (!IsPostBack) {
// load the data from the database in here
}
Related
Cardview Columns using Devexpress
created a few seconds ago Hi, I am creating a web page in asp.net based on data from a database. This should result in a number of tab pages with card views on each tab with 5 columns and a maximum of 20 rows. The tab pages are working, the rows are working but the columns will not change from the default 3 columns. I have tried setting the columnCount property at different stages, post and pre databinding. This getting frustrating. I am having problems with setting a card views column count programmatically. I am setting it, have tried to set it in different places but it always goes to the default 3 columns :( I am using C# in Visual studio 2017. Here is the code I am using: SqlDataSource sds = new SqlDataSource(); public string fName; protected void Page_Load(object sender, EventArgs e) { string fid = Request.QueryString["FID"]; sds.ConnectionString = ConfigurationManager.ConnectionStrings["DataBaseConnection"].ToString(); sds.SelectCommand = "select name from [flashboard] where flashboardid = " + fid; DataView fDet = (DataView)sds.Select(DataSourceSelectArguments.Empty); fName = fDet.Table.Rows[0]["name"].ToString(); TitleLink.InnerHtml = fName; sds.SelectCommand = "SELECT flashboardtabid, name FROM [FlashboardTab] WHERE flashboardid = " + fid+" order by SeqNo"; DataView fTab = (DataView)sds.Select(DataSourceSelectArguments.Empty); TabPage tabDet; ASPxPageControl tpc = ASPxPageControl1; ASPxCardView cardGrp; CardViewTextColumn cName; CardViewHyperLinkColumn cEvidence; foreach (DataRow tab in fTab.Table.Rows) { tabDet = new TabPage(); tabDet.Text = tab["name"].ToString(); tabDet.Name = "Tab"+tab["flashboardtabid"].ToString(); tabDet.ActiveTabStyle.Width = Unit.Percentage( 80); cardGrp = new ASPxCardView(); cardGrp.ID = "CardGroup" + tab["flashboardtabid"].ToString() ; tabDet.Controls.Add(cardGrp); tpc.TabPages.Add(tabDet); cardGrp.AutoGenerateColumns = false; ASPxCardViewPagerSettings cvps = new ASPxCardViewPagerSettings(cardGrp); cardGrp.EnableTheming = true; cardGrp.Theme = "SoftOrange"; cvps.Visible = false; cvps.SettingsTableLayout.ColumnCount = 5; cvps.SettingsTableLayout.RowsPerPage = 20; cardGrp.DataSource = GetData("SELECT cardid, Description, EvidencePage, SmartViewid FROM [flashboardcard] WHERE flashboardtabid = "+tab["flashboardtabid"] + " order by SeqNo"); cardGrp.Attributes.Add("Width", "80%"); cardGrp.Attributes.Add("style", "margin:auto"); cName = new CardViewTextColumn(); cName.Name = "Description"; cName.FieldName = "Description"; cEvidence = new CardViewHyperLinkColumn(); cEvidence.Name = "EvidencePage"; cEvidence.FieldName = "EvidencePage"; cEvidence.PropertiesHyperLinkEdit.Text = "Evidence"; cardGrp.Columns.Add(cName); cardGrp.Columns.Add(cEvidence); var layoutitem1 = new CardViewColumnLayoutItem(); // cardGrp.CardLayoutProperties.FindColumnItem("EvidencePage"); layoutitem1.ColumnName = "EvidencePage"; layoutitem1.ShowCaption = DevExpress.Utils.DefaultBoolean.False; layoutitem1.HorizontalAlign = FormLayoutHorizontalAlign.Center; var layoutitem2 = new CardViewColumnLayoutItem(); layoutitem2.ColumnName = "Description"; layoutitem2.ShowCaption = DevExpress.Utils.DefaultBoolean.False; layoutitem2.HorizontalAlign = FormLayoutHorizontalAlign.Center; layoutitem2.ParentContainerStyle.Font.Bold = true; layoutitem2.ParentContainerStyle.Font.Size = FontUnit.Medium; cardGrp.CardLayoutProperties.Items.Add(layoutitem2); cardGrp.CardLayoutProperties.Items.Add(layoutitem1); cardGrp.DataBind(); } } DataView GetData(String queryString) { DataView ds = new DataView(); sds.SelectCommand = queryString; ds = (DataView)sds.Select(DataSourceSelectArguments.Empty); return ds; }
To resolve this issue with ColumnCount, I recommend you define it directly in the control's SettingsPager.SettingsTableLayout.ColumnCount property instead of specifying it in a new ASPxCardViewPagerSettings instance: cardGrp.SettingsPager.SettingsTableLayout.ColumnCount = 5; cardGrp.SettingsPager.SettingsTableLayout.RowsPerPage = 20;
c# winforms change text of programmatically made tabpage
I made a language switch (English, Polski) and I wanted to if tabpage contains word "New " then change it to "Nowy " and vice-versa, but I have one problem. This tabPage is made programmatically and I don't know, how to change it's header's text. I made this: private void englishToolStripMenuItem_Click(object sender, EventArgs e) { Class1.LangNumber = 2; Class1.ChangeLanguage(2); polskiToolStripMenuItem.Checked = false; englishToolStripMenuItem.Checked = true; fileToolStripMenuItem.Text = Class1.file; openToolStripMenuItem.Text = Class1.open; saveToolStripMenuItem.Text = Class1.save; saveAsToolStripMenuItem.Text = Class1.saveas; edjtToolStripMenuItem.Text = Class1.edit; cutToolStripMenuItem.Text = Class1.cut; copyToolStripMenuItem.Text = Class1.copy; pasteToolStripMenuItem.Text = Class1.paste; selectAllToolStripMenuItem.Text = Class1.selectall; deselectAllToolStripMenuItem.Text = Class1.deselectall; dateAndTimeToolStripMenuItem.Text = Class1.dateandtime; nicknameToolStripMenuItem.Text = Class1.nickname; autoWordSelectionToolStripMenuItem.Text = Class1.awsel; tabManagementToolStripMenuItem.Text = Class1.tabmgmt; newTabToolStripMenuItem.Text = Class1.ntab; deleteSelectedTabToolStripMenuItem.Text = Class1.dtab; infoToolStripMenuItem.Text = Class1.iands; electryNotepadInfoToolStripMenuItem.Text = Class1.info; setNicknameToolStripMenuItem.Text = Class1.setnickname; languagesToolStripMenuItem.Text = Class1.lang; nicknamerror = Class1.nicknameloaderror; savedialog = Class1.saved; savedialogcap = Class1.savecap; nicknameerrorcap = Class1.nlecap; ncreate = Class1.ncreation; ncreatecap = Class1.ncreationcap; setnicknamedialog = Class1.setnicknamedialog; newtab = Class1.nev; for (int i = 0; i <= tabControl1.TabCount - 1; i++) { TabPage t = tabControl1.TabPages[i]; if (t.Text.Contains("Nowy")) { t.Text.Replace("Nowy", "New"); } Application.DoEvents(); } } private void polskiToolStripMenuItem_Click(object sender, EventArgs e) { Class1.LangNumber = 1; Class1.ChangeLanguage(1); polskiToolStripMenuItem.Checked = true; englishToolStripMenuItem.Checked = false; fileToolStripMenuItem.Text = Class1.file; openToolStripMenuItem.Text = Class1.open; saveToolStripMenuItem.Text = Class1.save; saveAsToolStripMenuItem.Text = Class1.saveas; edjtToolStripMenuItem.Text = Class1.edit; cutToolStripMenuItem.Text = Class1.cut; copyToolStripMenuItem.Text = Class1.copy; pasteToolStripMenuItem.Text = Class1.paste; selectAllToolStripMenuItem.Text = Class1.selectall; deselectAllToolStripMenuItem.Text = Class1.deselectall; dateAndTimeToolStripMenuItem.Text = Class1.dateandtime; nicknameToolStripMenuItem.Text = Class1.nickname; autoWordSelectionToolStripMenuItem.Text = Class1.awsel; tabManagementToolStripMenuItem.Text = Class1.tabmgmt; newTabToolStripMenuItem.Text = Class1.ntab; deleteSelectedTabToolStripMenuItem.Text = Class1.dtab; infoToolStripMenuItem.Text = Class1.iands; electryNotepadInfoToolStripMenuItem.Text = Class1.info; setNicknameToolStripMenuItem.Text = Class1.setnickname; languagesToolStripMenuItem.Text = Class1.lang; nicknamerror = Class1.nicknameloaderror; savedialog = Class1.saved; savedialogcap = Class1.savecap; nicknameerrorcap = Class1.nlecap; ncreate = Class1.ncreation; ncreatecap = Class1.ncreationcap; setnicknamedialog = Class1.setnicknamedialog; newtab = Class1.nev; for(int i = 0; i <= tabControl1.TabCount - 1; i++) { TabPage t = tabControl1.TabPages[i]; if(t.Text.Contains("New")) { t.Text.Replace("New", "Nowy"); } Application.DoEvents(); } } The Class1 file: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectryNotepad { public static class Class1 { public static string file = "Plik"; public static string open = "Otwórz"; public static string save = "Zapisz"; public static string saveas = "Zapisz jako"; public static string edit = "Edycja"; public static string cut = "Wytnij"; public static string copy = "Kopiuj"; public static string paste = "Wklej"; public static string selectall = "Zaznacz wszystko"; public static string deselectall = "Odznacz wszystko"; public static string dateandtime = "Data i Godzina"; public static string nickname = "Nazwa"; public static string awsel = "Automatyczne zaznaczanie słów"; public static string tabmgmt = "Zarządzanie zakładkami"; public static string ntab = "Nowa zakładka"; public static string dtab = "Usuń zaznaczoną zakładkę"; public static string iands = "Informacje i ustawienia"; public static string info = "ElectryNotepad - Informacje"; public static string setnickname = "Ustaw nazwę"; public static string nicknameloaderror = "Nie ustawiłeś swojej nazwy. Proszę kliknąć opcję \"Ustaw nazwę\" w \"Informacje i Ustawienia\"."; public static string nlecap = "Błąd nazwy"; public static string setnicknamedialog = "Proszę wpisz swoją nazwę w pole tekstowe poniżej (max 32 znaki) \n \n UWAGA! POPRZEDNIA NAZWA ZOSTANIE USUNIĘTA!"; public static string ncreation = "\n \n Czy na chcesz ustawić tą nazwę?"; public static string ncreationcap = "Asystent ustawiania nazwy"; public static string nev = "Nowy "; public static string saved = "Czy chcesz zapisać swoją pracę?"; public static string savecap = "Zapisywanie"; public static string lang = "Język"; public static bool Polish = true; public static int LangNumber = 1; public static void ChangeLanguage(int l) { switch(l) { case 1: Polish = true; lang = "Język"; file = "Plik"; open = "Otwórz"; save = "Zapisz"; saveas = "Zapisz jako"; edit = "Edycja"; cut = "Wytnij"; copy = "Kopiuj"; paste = "Wklej"; selectall = "Zaznacz wszystko"; deselectall = "Odznacz wszystko"; dateandtime = "Data i Godzina"; awsel = "Automatyczne zaznaczanie słów"; tabmgmt = "Zarządzanie zakładkami"; nickname = "Nazwa"; ntab = "Nowa zakładka"; dtab = "Usuń zaznaczoną zakładkę"; iands = "Informacje i ustawienia"; info = "ElectryNotepad - Informacje"; setnickname = "Ustaw nazwę"; nicknameloaderror = "Nie ustawiłeś swojej nazwy. Proszę kliknąć opcję \"Ustaw nazwę\" w \"Informacje i Ustawienia\"."; nlecap = "Błąd nazwy"; setnicknamedialog = "Proszę wpisz swoją nazwę w pole tekstowe poniżej (max 32 znaki) \n \n UWAGA! POPRZEDNIA NAZWA ZOSTANIE USUNIĘTA!"; ncreation = "\n \n Czy na chcesz ustawić tą nazwę?"; ncreationcap = "Asystent ustawiania nazwy"; nev = "Nowy "; saved = "Czy chcesz zapisać swoją pracę?"; savecap = "Zapisywanie"; break; case 2: Polish = false; lang = "Language"; file = "File"; open = "Open"; save = "Save"; saveas = "Save as"; edit = "Edit"; cut = "Cut"; copy = "Copy"; paste = "Paste"; dateandtime = "Date and time"; selectall = "Select All"; deselectall = "Deselect All"; awsel = "Auto Word Selection"; tabmgmt = "Tab Management"; nickname = "Nickname"; ntab = "New Tab"; dtab = "Delete Selected Tab"; iands = "Info and Settings"; info = "ElectryNotepad - Info"; setnickname = "Set Nickname"; nicknameloaderror = "You didn't set nickname. Please, press \"Set Nickname\" in \"Info and Settings\"."; nlecap = "Nickname error"; setnicknamedialog = "Please type your nickname in text field below (max 32 characters) \n \n CAUTION! PREVIOUS NICKNAME WILL BE DELETED!"; ncreation = "\n \n Are you sure you want to set this nickname?"; ncreationcap = "Nickname creation assistant"; nev = "New "; saved = "Do you want to save this?"; savecap = "Saving"; break; } } } } But it doesn't work. When I click button for Polski, or for English it doesn't change anything. Help me, please.
Your all concept is wrong. You should use translation mechanism for such work. Externalizing the translation of a WinForms application?
OK, ok. I realized I cam make another way to translate my program. I can make reading from file in search for text and applying it to these strings. Thread closed
Filling textboxes with strings
I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string? Here is what I have. var client = new WebClient { Credentials = new NetworkCredential(username, password) }; var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume"); var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + ""); JObject rss = JObject.Parse(jss); JObject fin = JObject.Parse(financials); string RRSTITLE = (string)rss["legal_name"]; string beta = (string)fin.SelectToken("data[0].value"); string marketcap = (string)fin.SelectToken("data[1].value"); string weekhigh = (string)fin.SelectToken("data[2].value"); string weeklow = (string)fin.SelectToken("data[3].value"); string adj_close = (string)fin.SelectToken("data[4].value"); string short_interest = (string)fin.SelectToken("data[5].value"); string analyst_target = (string)fin.SelectToken("data[6].value"); string earnings = (string)fin.SelectToken("data[7].value"); string percent_change = (string)fin.SelectToken("data[8].value"); string yr_percent_change = (string)fin.SelectToken("data[9].value"); string implied = (string)fin.SelectToken("data[10].value"); string divyield = (string)fin.SelectToken("data[11].value"); string exchange = (string)fin.SelectToken("data[12].value"); string sector = (string)fin.SelectToken("data[13].value"); string volume = (string)fin.SelectToken("data[14].value"); company_textbox.Text = RRSTITLE; beta_box.Text = beta; marketCap_box.Text = marketcap; wekhighbox.Text = weekhigh; weklowbox.Text = weeklow; adjclosebox.Text = adj_close; shortbox.Text = short_interest; targetestbox.Text = analyst_target; next_earnings.Text = earnings; Close_box.Text = percent_change; percentytd.Text = yr_percent_change; implivolbox.Text = implied; divyieldbox.Text = divyield; exchangebox.Text = exchange; sectorbox.Text = sector; daily_Volume_text.Text = volume;
Like #Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>(); Dictionary<string, string> ValueLookup = new Dictionary<string, string>(); TextBoxLookup["beta"] = beta_box; TextBoxLookup["marketcap"] = marketCap_box; TextBoxLookup["weekhigh"] = wekhighbox; ValueLookup["beta"] = beta; ValueLookup["marketcap"] = marketcap; ValueLookup["weekhigh"] = weekhigh; foreach(string key in TextBoxLookup.Keys) { TextBoxLookup[key].Text = ValueLookup[key]; } You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign. Does this help?
Get data from SQL datebase and return as string
Need help to get the 1st row record and return record as string in the << >> after while() loop. There are a lot of columns in one row, I'm having a problem to declare it as string st? like usually string st = new string() please help to correct it Thanks public string Get_aodIdeal(string SubmittedBy) { String errMsg = ""; Guid? rguid = null; int isOnContract = 0; int isFreeMM = 0; string _FileName; DateTime InstallDateTime = DateTime.Now; string FileDate = ToYYYYMMDD(DateTime.Now); errMsg = "Unknown Error."; SqlConnection conn = null; SqlCommand cmd = null; string st = null; conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["iDeal"].ConnectionString); cmd = new SqlCommand(); string SQL = "select TOP 1 * from table1 Order by SubmittedOn desc"; SqlDataAdapter sqd = new SqlDataAdapter(SQL, conn); cmd.CommandTimeout = 1200; conn.Open(); SqlDataReader sqr; //sqd.SelectCommand.Parameters.Add("#Submitted", SqlDbType.Int).Value = PostID; sqr = sqd.SelectCommand.ExecuteReader(); while (sqr.Read()) st = new string{ rguid = cmd.Parameters["#rguid"].Value as Guid?, ridno = int.Parse(sqr["ridno"].ToString()), SubmittedOn= DateTime.Parse(sqr["SubmittedOn"].ToString()), SubmittingHost = sqr["SubmittingHost"].ToString(), ServiceAgreementNo = sqr["ServiceAgreementNo"].ToString(), DocumentID = sqr["DocumentID"].ToString(), Source = sqr["Source"].ToString(), FileName = sqr["FileName"].ToString(), FileType = sqr["FileType"].ToString(), FileDate = DateTime.Parse(sqr["FileDate"].ToString()), InstallTime = DateTime.Parse(sqr["InstallTime"].ToString()), CalenderCode = cmd.Parameters["CalenderCode"].Value as Guid, isFreeMM = bool.Parse(sqr["isFreeMM"].ToString()), isOnContract = bool.Parse(sqr["isOnContract"].ToString()), isProcessed = bool.Parse(sqr["isProcessed"].ToString()), ProcessedByFullName = sqr["ProcessedByFullName"].ToString(), isDelete = bool.Parse(sqr["isDelete"].ToString()), version = int.Parse(sqr["Version"].ToString()), LastUpdatedBy = DateTime.Parse(sqr["LastUpdatedBy"].ToString()), LastUpdatedOn = DateTime.Parse(sqr["LastUpdatedOn"].ToString()), shopGuid = sqr["shopGuid"].ToString(), MacID = sqr["MacID"].ToString(), MSISDN = sqr["MSISDN"].ToString() }
You can use a StringBuilder for this purpose as like the following: StringBuilder strBuilder= new StringBuilder(); while (sqr.Read()) { strBuilder.AppendFormat("PostID : {0}{1}",sqr["PostID"].ToString(),Environment.NewLine); strBuilder.AppendFormat("dateposted : {0}{1}",sqr["dateposted"].ToString(),Environment.NewLine); // And so on Build your string } Finally the strBuilder.ToString() will give you the required string. But More smarter way is Create a Class with necessary properties and an Overrided .ToString method for display the output. Let AodIdeal be a class with an overrided ToString() method. And Let me defined it like the following : public class AodIdeal { public int PostID { get; set; } public string dateposted { get; set; } public string Source { get; set; } // Rest of properties here public override string ToString() { StringBuilder ObjectStringBuilder = new StringBuilder(); ObjectStringBuilder.AppendFormat("PostID : {0}{1}", PostID, Environment.NewLine); ObjectStringBuilder.AppendFormat("dateposted : {0}{1}",dateposted, Environment.NewLine); ObjectStringBuilder.AppendFormat("Source : {0}{1}", Source, Environment.NewLine); // and so on return ObjectStringBuilder.ToString(); } } Then you can create an object of the class(let it be objAodIdeal), and make use of its properties instead for the local variables. And finally objAodIdeal.ToString() will give you the required output. Example usage AodIdeal objAodIdeal= new AodIdeal(); while (sqr.Read()) { objAodIdeal.PostID = int.Parse(sqr["PostID"].ToString()); objAodIdeal.dateposted= sqr["dateposted"].ToString(); // assign rest of properties } string requiredString= objAodIdeal.ToString();
How can i set up all the data's in the textbox
first of all there is a searchbox form and a view form. after passing the value of the id in the searchbox, it should return all the values that matches with the id of that person after the textchange method occured. but it doesn't display a single value on the textboxes. here is my code public void first_tab_search(string key) { key = txtSearch.Text; var first = from a in dbcon.personal_informations where a.last_name == key select a; foreach (var setThem in first) { txtsurname.Text = setThem.last_name; txtfirstname.Text = setThem.first_name; txtmiddlename.Text = setThem.middle_name; txtID.Text = setThem.userid; txtweight.Text = setThem.weight; txttin.Text = setThem.tin; txtsss.Text = setThem.sss; txtaeno.Text = setThem.agency_employee_no; txtbloodtype.Text = setThem.blood_type; txtcitizenship.Text = setThem.citizenship; txtcivilstatus.Text = setThem.civil_status; txtcpno.Text = setThem.cell_no; txtdob.Text = setThem.datetime_of_birth.ToString(); txtemail.Text = setThem.email_address; txtgender.Text = setThem.sex; txtgsis.Text = setThem.gsis_id; txtheight.Text = setThem.height; txtnameext.Text = setThem.name_ext; txtpagibig.Text = setThem.pagibig_id; txtpermaaddr.Text = setThem.permanent_address; txtpermatelno.Text = setThem.permanent_telno; txtpermazip.Text = setThem.permanent_zipcode; txtphilhealth.Text = setThem.philhealth; txtpob.Text = setThem.place_of_birth; txtresidentialaddr.Text = setThem.residential_address; txtresitelno.Text = setThem.residential_telno; txtresizip.Text = setThem.residential_zipcode; txtweight.Text = setThem.weight; } }
You have a whole host of problems going on here. You pass a key into the method, and then immediately overwrite it with the contents of your search box. Your search could return more than one result, and therefore your code is looping through each result and overwriting the output values with the last returned row. Use += rather than + in your loop, i.e. txtsurname.Text += setThem.last_name; Your code is currently case sensitive, this may be the desired approach but might not be.