I'm filling up a database from an aspx web application.
Everything works fine, except for the fact that I use multiple pages for users to fill in their data into DB.
So, i got this method in one class.cs file:
public class Botones
{
public void SaveCVInfo2(string varOne,string varTwo, string varThree)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
This is just a part of the file, it has more columns, but it doesn't change the example.
However, I added another class.cs file in order to reference it's method from a button in the second page. Just like the one I posted before in this post:
public class Botones2
{
public void SaveCVInfo3(string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
AS you can see there are more columns I'm filling into the db, in the same table, problem is, when i submit data to the sql server, from second page, it just creates a new Usuario_web without the columns i referenced in first class.
What i need is to bind somehow the data already sent from first page. So first class is associated with all other classes, and columns are filled in the same row.
If anybody knows how to handle this situation, please let me know.
EDIT
This is how i call methods from asp buttons:
protected void Button1_Click(object sender, EventArgs e)
{
Botones botones = new Botones();
botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
}
And SaveCVInfo3:
protected void Button1_Click(object sender, EventArgs e)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
CAUTION: Untested code below.
I would return the columna.ID from SaveCVInfo2:
public int SaveCVInfo2(string varOne,string varTwo, string varThree)
{
int columnaId = 0;
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
columnaId = columna.ID;
}
return columnaId;
}
And call the method, get the ID and save in the Session like this:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
Botones botones = new Botones();
columnaId = botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
Session["columnaId"] = columnaId.ToString();
}
Now when calling the SaveCVInfo3 method, I can pass the columnaId:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
if(Session["columnaId"] != null && int.TryParse(Session["columnaId"].ToString(), out columnaId)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(columnaId, nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
}
And in SaveCVInfo3 method I would get the object by Id, which is already saved in previous page and edit it, save it:
public void SaveCVInfo3(int columnaId, string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
//You will need to add reference to Linq if not added already
//Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
//db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
EDIT If Id is not a primary key, you can change this part-
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
to :
Usuario_Web columna =(Usuario_Web)db.Usuario_Web.Where(x=>x.ID == columnaId).FirstOrDefault()
Related
I want these buttons created using a foreach loop from a list of items to access the information that is stored in these items.
I used a foreach loop to create buttons from a list of items that represent files in a directory and those items hold links to these files. My goal is to make pressing these buttons open a dialog with these files to write a line in them.
public List<mov.Movie> movies = new List<mov.Movie>() { };
private void writeReportToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (string file in Directory.EnumerateFiles(#"C:\Users\sloup\OneDrive\Desktop\MovieList", "*.txt"))
{
var lines = File.ReadAllLines(file);
string movieName = lines[0];
if (movies.Select(x => x.Name).Contains(movieName))
{
}
else
{
string movieLength = lines[1];
string movieYear = lines[2];
string movieReport = lines[3];
movies.Add(new mov.Movie(movieName, movieLength, movieYear, movieReport, #"C:\Users\sloup\OneDrive\Desktop\MovieList" + movieName + ".txt"));
}
}
int X = 1;
int Y = 1;
foreach (var movie in movies)
{
var movie1Button = new Button();
movie1Button.Text = movie.Name;
movie1Button.Font = new Font("Calibri", 12);
movie1Button.ForeColor = Color.Black;
movie1Button.Padding = new Padding(6);
movie1Button.AutoSize = true;
this.Controls.Add(movie1Button);
movie1Button.Location = new System.Drawing.Point(20, 50 * X);
X++;
movie1Button.Click += Movie1Button_Click;
var movie1Label = new Label();
movie1Label.Text = movie.Year;
movie1Label.Font = new Font("Calibri", 12);
movie1Label.ForeColor = Color.Black;
movie1Label.Padding = new Padding(6);
movie1Label.AutoSize = true;
this.Controls.Add(movie1Label);
movie1Label.Location = new System.Drawing.Point(200, 50 * Y);
Y++;
}
}
private void Movie1Button_Click(object? sender, EventArgs e)
{
string[] lines1 = File.ReadAllLines();
var lines = File.ReadAllLines();
string movieName = lines[0];
string movieLength = lines[1];
string movieYear = lines[2];
}
public class Movie
{
public string Name;
public string Length;
public string Year;
public string Report;
public string Link;
public Movie(string movieName, string movieLength, string movieYear, string movieReport, string movieLink)
{
Name = movieName;
Length = movieLength;
Year = movieYear;
Report = movieReport;
Link = movieLink;
}
}
You can use the Tag property to attach the movie object to each button in the loop:
movie1Button.Tag = movie;
afterwards in the click event grab the button from the sender and cast the Tag-object back to a Movie
private void Movie1Button_Click(object? sender, EventArgs e)
{
Button button = sender as Button
(if button != null)
{
Movie movie = button.Tag as Movie;
// do what ever you like afterwards
}
}
private void EmployeeContractAction_Execute(object sender, SimpleActionExecuteEventArgs e)
{
Employee detail;
PropertyCollectionSource em = (PropertyCollectionSource)((ListView)View).CollectionSource;
detail = (Employee)em.MasterObject;
ShowViewParameters svpInternal = new ShowViewParameters();
XPObjectSpace objSpaceNew = (XPObjectSpace)ObjectSpace.CreateNestedObjectSpace();
Employee objEmp = (Employee)objSpaceNew.GetObject(detail);
EmployeeContract objReg;
objReg = null;
if (objReg == null)
{
objReg = new EmployeeContract(objSpaceNew.Session);
}
objReg.Employee = objEmp;
svpInternal.CreatedView = Application.CreateDetailView(objSpaceNew, "EmployeeContract_DetailView2", true, objReg);
svpInternal.TargetWindow = TargetWindow.NewModalWindow;
svpInternal.Context = TemplateContext.View;
Application.ShowViewStrategy.ShowView(svpInternal, new ShowViewSource(null, null));
objReg.Save();
ObjectSpace.CommitChanges();
//View.ObjectSpace.Refresh();
}
I created this code, if I added new data it can't be saved, but if I edit existing data, it is will be changed. Can anyone help me?
public partial class DataGrid_HBD : UserControl
{
public DataGrid_HBD()
{
InitializeComponent();
// 2 Seconds Timer before connecting to the Database.
// This improves UI rendering on button click
DataGrid_Data();
}
/// <summary>
/// Loading Data Grid
/// </summary>
public void DataGrid_Data()
{
// 2 second delay before loading DataGrid
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Start();
timer.Tick += (sender, args) =>
{
timer.Stop();
// Attempt to connect to SQL Server database and populate DataGrid with database tables.
try
{
string connectionString = ("Data Source=\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT [hb_Disputes].[DSP_ID], [hb_disputes].[ACCOUNT], [Users].[TX_EMPLOYEE], [hb_CsrNames].[NM_USER], [hb_disputes].[CUST_NAME],[hb_disputes].[PREM_ADDR], [hb_status].[Status], [hb_disputes].[OPENED], [hb_disputes].[DEADLINE], [hb_disputes].[DATERSLVD], [hb_rpttype].[ReportType], [hb_ratetype].[RateType], [hb_Disputes].[FR_DT_FIRSTREV], [hb_Disputes].[FR_TS_LATESTUPD], [hb_Disputes].[COMMENT], [hb_Disputes].[FR_DSP_CLSF], [hb_Disputes].[FR_CUST_CNTCT], [hb_Disputes].[FR_WRK_REQ], [hb_Disputes].[FR_OPN_ERR], [hb_Disputes].[FR_SO_TP], [hb_Disputes].[FR_SO_DTLS], [hb_Disputes].[FR_SO_DT_WNTD], [hb_Disputes].[FR_SO_ISSD_BY], [hb_Disputes].[FR_CMMNT] FROM [hb_disputes]" +
" LEFT JOIN [Users] ON [hb_disputes].[ASSGNTO] = [Users].[KY_USER_ID] LEFT JOIN [hb_CsrNames] ON [hb_disputes].[WFMUSER] = [hb_CsrNames].[KY_USER_ID] LEFT JOIN [hb_status] ON [hb_disputes].[STATUS] = [hb_status].[STSID] LEFT JOIN [hb_rpttype] ON [hb_disputes].[RPTTYPE] = [hb_rpttype].[RPTID] LEFT JOIN [hb_ratetype] ON [hb_disputes].[REV_CLS] = [hb_ratetype].[RTID]", connection);
connection.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
connection.Close();
dtGrid.DataContext = dt;
}
catch
{
MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
}
};
}
private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// User double clicks on DataGrid Row
// Open new Window
// Populate selected textboxes with selected datarow
DataGrid gd = (DataGrid)sender;
DataRowView row_selected = gd.SelectedItem as DataRowView;
var windowToOpen = new Window1();
if(gd !=null )
{
// Textboxes
windowToOpen.txt_RowRecrd.Text = row_selected["DSP_ID"].ToString();
windowToOpen.txt_acctnumber.Text = row_selected["ACCOUNT"].ToString();
windowToOpen.txt_analyst.Text = row_selected["TX_EMPLOYEE"].ToString();
windowToOpen.txt_custname.Text = row_selected["CUST_NAME"].ToString();
windowToOpen.txt_address.Text = row_selected["PREM_ADDR"].ToString();
windowToOpen.txt_Status.Text = row_selected["Status"].ToString();
windowToOpen.txt_opened.Text = row_selected["OPENED"].ToString();
windowToOpen.txt_deadline.Text = row_selected["DEADLINE"].ToString();
windowToOpen.txt_DateResolved.Text = row_selected["DATERSLVD"].ToString();
windowToOpen.txt_revcls.Text = row_selected["RateType"].ToString();
windowToOpen.txt_WFMissuedBy.Text = row_selected["NM_USER"].ToString();
windowToOpen.txt_firstreview.Text = row_selected["FR_DT_FIRSTREV"].ToString();
windowToOpen.txt_Latestupdate.Text = row_selected["FR_TS_LATESTUPD"].ToString();
windowToOpen.txt_reviewNotes.Text = row_selected["FR_CMMNT"].ToString();
windowToOpen.txt_ResolutionNotes.Text = row_selected["COMMENT"].ToString();
// Comboboxes
windowToOpen.cmb_UtilityRptTyp.SelectedItem = row_selected["ReportType"].ToString();
windowToOpen.Show();
}
else
{
return;
}
}
When the user double clicks on a row in the Datagrid, it opens a new window and populates the textboxes with the selected cells. However, it does not work for CombinationBoxes. I attached an image of the new window (Window1) that the information is populating to. The image shows the code behind for the combobox with the populated table from the SQL Server database.
First of all, You must set Datasource of cmb_UtilityRptTyp with a list of available report types like this:
// Define ReportType Class
class ReportType {
public int ID { get; set; }
public string Title { get; set; }
public ReportType(int id, string title)
{
ID = id;
Title = title;
}
}
Then set DataSource in first line of dtGrid_MouseDoubleClick:
ReportType[] list = new ReportType[] {
new ReportType(1, "Type 1"),
new ReportType(2, "Type 2"),
};
windowToOpen.cmb_UtilityRptTyp.DataSource = list;
windowToOpen.cmb_UtilityRptTyp.DisplayMember = "Title";
windowToOpen.cmb_UtilityRptTyp.ValueMember = "ID";
After that you must use the SelectedText instead of Text in ComboBox, like this:
windowToOpen.cmb_UtilityRptTyp.SelectedText = row_selected["RPTTYPE"].ToString();
Also, You can use SelectedIndex, to find item index you could IndexOf like this
string rptType = row_selected["RPTTYPE"].ToString();
int index = windowToOpen.cmb_UtilityRptTyp.Items.IndexOf(rptType );
windowToOpen.cmb_UtilityRptTyp.SelectedIndex = index;
Or use FindStringExact
string rptType = row_selected["RPTTYPE"].ToString();
int index = windowToOpen.cmb_UtilityRptTyp.FindStringExact(rptType );
windowToOpen.cmb_UtilityRptTyp.SelectedIndex = index;
I am trying to delete the record from an entity
got an error: Invalid operation exception
The object cannot be deleted because it was not found in the ObjectStateManager.
and the code is like this...
private void btnProdDelete_Click(object sender, EventArgs e){
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
//var c = new category {
// category_Name = tbCategoryName.Text,
// category_Description = tbCategoryDescription.Text
//};
product pd = new product();
pd.product_Id = productid;
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;
tsgentity.DeleteObject(pd);
this.Close();
}
would any one pls help on this...
Modified code :
public partial class ProductDescriptionForm : Form {
public TsgEntities tsgentity;
public ProductDescriptionForm() {
InitializeComponent();
tsgentity = new TSGEntities();
}
The problem is that you are trying to delete an object that is not tracked by the context.
The proper way to delete without fetching is to create an instance (only the id is actually needed), attach it to the context and then delete it :
var pd =
new product()
{
product_Id = productid,
EntityKey = new EntityKey("product.id", "id", productid)
};
tsgentity.Attach(pd);
tsgentity.DeleteObject(pd);
I have a datagridview in my form. It fills by selecting country with cities of country.I have set the property (AllowUsersToAddRow = True)
but when i run my project user can't add or edit or delete any row.I checked it.It is not readonly(readonly = false) and It is enable (Enabled = true)
What's the problem?
Code of fill datagridview:
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex>=0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
dgvValues.DataSource = from record in Program.dal.Cities(CountryId) select new { record.City};
}
If you find this question useful don't forgot to vote it.
To give a simplified example, if I do the equivalent of your query, such as:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
dataGridView.DataSource = cities;
I get the same result as you - no option to add new rows, but if I change to BindingList<T> and set this to AllowNew it all works:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
var citiesBinding = new BindingList<City>(cities);
citiesBinding.AllowNew = true;
dataGridView.DataSource = citiesBinding;
EDIT - with a solution for your particular example:
private class City
{
public string Name { get; set; }
}
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex >= 0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
var queryResults = from record in Program.dal.Cities(CountryId) select new City { Name = record.City };
var queryBinding = new BindingList<City>(queryResults.ToList());
queryBinding.AllowNew = true;
dgvValues.DataSource = queryBinding;
}
Note that a) I had to change the anonymous type in the query select into a concrete type City and also change the IEnumerable<T> returned by Linq query to an IList<T> compatible type to create the BindingList<T>. This should work, however :)