Error doesn't let me update data into my database - c#

Error: Invalid column name 'Id'.'
I've been trying to make an update function, the logic behind it I think is fine, but it keeps throwing me this error mentioned above.
internal static void Uredi(Zahtjev odabraniZapis)
{
DB.OpenConnection();
string sql = $"UPDATE Zahtjev_za_nabavu SET Ponuda = '{odabraniZapis.Ponuda}', Opis_predmeta = '{odabraniZapis.Opis_predmeta}', Cijena = '{odabraniZapis.Cijena}', ID_zaposlenika = {odabraniZapis.ID_zaposlenika} WHERE ID_zahtjeva = {odabraniZapis.ID_zahtjeva};";
DB.ExecuteCommand(sql);
DB.CloseConnection();
}
This above is the function that I call to Update existing data.
I get the row that i want to change through ID_zahtjeva .
And this is the function that calls the UPDATE function.
private void btnAzuriraj_Click(object sender, EventArgs e)
{
Zahtjev noviZahtjev = new Zahtjev(int.Parse(txtZahtjev.Text), txtPonuda.Text, txtOpis.Text, txtCijena.Text, int.Parse(txtZaposlenik.Text));
var provjera = ZahtjeviRepository.GetZahtjevi(noviZahtjev.ID_zahtjeva);
if(provjera == null)
{
ZahtjeviRepository.Kreiraj(noviZahtjev);
this.Close();
}
else
{
ZahtjeviRepository.Uredi(noviZahtjev);
this.Close();
}
}

Related

Stripe.Net Create and Update user

Im very new to programing and new to stripe. i am currently trying to create a basic page where i can just create the customers. Im currently using the stripe.net dll and am having a hard time getting this page to work correctly. Here is what i have. I get no errors and no records get created.
Using Stripe;
private StripeCustomer GetCustomer()
{
var mycust = new StripeCustomerCreateOptions();
mycust.Email = "thisisit#overhere.com";
mycust.Description = "One Time";
mycust.CardName = "Full Name";
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.Create(mycust);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer current = GetCustomer();
var mycharge = new StripeChargeCreateOptions();
string key = System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"];
Response.Redirect("/services/donate/thanks.aspx");
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Also a little help (as i am lost an nothing i try works) as to how i would go about pulling a list of the current customs i have and display them would be great.
I'm guessing you're using this: https://github.com/jaymedavis/stripe.net#list-all-customers
In your GetCustomer method you are creating a customer, instead, you want to do something like the following:
private IEnumerable<StripeCustomer> GetCustomers()
{
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.List();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer list = GetCustomers();
//show this list somewhere
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Makre sure StripeApiKey exists in your configuration file.

Calling an SQL stored procedure that's defined in a method using button click on form c#

Having a lot of trouble with this. I'm working on a large project, so there's only a few classes I'm interested in and working on. Basically, these are forms - one is a main editor where a user edits details and the other is used to assign a pin number. In the main editor form, if the user has a pin, they can choose to edit this pin. Here's where my problem lies - if I edit the pin, what I'm doing in the code is deleting the old pin and adding the new one. However, the database doesn't update until AFTER the editor form is closed. Therefore, I'd like to call the method that does change the database on the OKButton click, if I could. The problem I'm facing is I don't know how.
Here is the DB code, we'll say the class is called DetailsConn:
public string editPin(int driverID)
{
if (SchemaChecker.PINAvailable())
{
string sql = "EditPIN";
using (SqlCommand cmd = new SqlCommand(sql, base.connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Remove("#nDriverID");
cmd.Parameters.AddWithValue("#nDriverID", driverID);
cmd.Parameters.Remove("#nPIN");
SqlParameter pinParameter = cmd.Parameters.Add("#nPIN", SqlDbType.Char);
pinParameter.Direction = ParameterDirection.Output;
pinParameter.Size = 32;
cmd.ExecuteNonQuery();
return pinParameter.Value.ToString();
}
}
return "";
}
Here's the code for my edit:
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.listViewDriverTags.SelectedItems.Count > 0)
{
ListViewItem lvi = this.listViewDriverTags.SelectedItems[0];
DriverTag driverTag = lvi.Tag as DriverTag;
else if (blahTag.blahType == 2)
{
buttonAssignPIN_Click(sender, e);
}
//message stuff and dialog boxes with localization info
if (dr == DialogResult.Yes)
{
this.listViewDriverTags.Items.Remove(lvi);
if (Tag.id != -1)
{
TagsToBeDeleted.Add(driverTag);
}
}
if (dr == DialogResult.No)
{
this.listViewTags.Items.Clear();
this.listViewTags.Items.Add(lvi);
}
}
}
Here's my buttonAssignPIN stuff:
private void buttonAssignPIN_Click(object sender, EventArgs e)
{
using (AssignPINForm form = new AssignPINForm())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
DriverTag PIN = DriverTag.GetNewPIN(form.DriverTag);
ListViewItem lvi = this.listViewTags.Items.Add(PIN.driverTag);
lvi.SubItems.Add(this.TagTypes[PIN.TagType]);
lvi.Tag = PIN;
}
}
}
And finally, here's my AssignPINForm code:
public partial class AssignPINForm : Form
{
public AssignPINForm()
{
InitializeComponent();
this.buttonOK.Click += new EventHandler(buttonOK_Click);
this.buttonCancel.Click += new EventHandler(buttonCancel_Click);
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"^[0-9]{4,20}$";
Regex regex = new Regex(pattern);
buttonOK.Enabled = regex.IsMatch(textBoxPin.Text);
};
LoadStrings();
}
public void LoadStrings()
{
//stome stuff
}
public string DriverTag
{
get { return this.textBoxPin.Text; }
set { this.textBoxPin.Text = value; }
}
private void buttonOK_Click(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void AssignPINForm_Load(object sender, EventArgs e)
{
}
}
I know it's kind of all over the place but I've provided everything I think is relevant. The middle two snippets are in the same class too, and the DB stuff is the same solution but a different project. I'd be grateful if someone can decipher what I'm after and help me out, it's the only thing I have left to do on this particular bit!
Thanks!
Not sure I fully got what you're after and I agree with some of the comments that this isn't the best of practice but I guess what you're after is to update the buttonOK_Click method to something like this:
private void buttonOK_Click(object sender, EventArgs e)
{
using(DetailsConn connection = new DetailsConn())
{
int driver = -1;
if(int.TryParse(this.DriverTag, out driver)) {
connection.editPin(driver);
}
}
}
Also, you may want to remove any other possible references to the editPin() function.
I actually figured out that even if I got that working correctly, it wasn't going to solve my problem. I've had to call a new procedure and declare that in the database schema - basically it was a lot more complicated than what I was giving it credit for. Thanks for the responses nonetheless.

The object cannot be deleted because it was not found in the ObjectStateManager #2

I get the problem in the screenshot:
Here is the code at the beginning of the program:
public MainWindow()
{
InitializeComponent();
BlackoutDates();
variables.date = Convert.ToDateTime(MainCalendar.DisplayDate);
DateOutput.Content = MainCalendar.DisplayDate.DayOfWeek + ", " + MainCalendar.DisplayDate.ToShortDateString();
}
//initialises entities
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
private Booking ObjectIndex;
Here is the code when the window is loaded
private void Bookings_Loaded(object sender, RoutedEventArgs e)
{
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
// Load data into Rooms.
var roomsViewSource = ((CollectionViewSource)(this.FindResource("roomsViewSource")));
var roomsQuery = this.GetRoomsQuery(allensCroftEntities1);
roomsViewSource.Source = roomsQuery.Execute(MergeOption.AppendOnly);
}
Here is the code for the delete button which causes the error:
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
//prevents user trying to delete nothing/unselected row
if (ObjectIndex == null)
{
MessageBox.Show("Cannot delete the blank entry");
}
else
{
//deletes object from dataset, saves it and outputs a message
allensCroftEntities1.DeleteObject(ObjectIndex);
allensCroftEntities1.SaveChanges();
MessageBox.Show("Booking Deleted");
}
}
Here is the code for the object index:
private void listrow_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//outputs index of the selected room
ObjectIndex = listrow.SelectedItem as Booking;
}
EDIT,
i tried
allensCroftEntities1.Attach(ObjectIndex);
EDIT,
When i comment out the entities in the bookings loaded event, I get this error, this code used to work fine, but i dont know why all of these problems are occurring.
Try attaching entity to the context first:
allensCroftEntities1.Attach(ObjectIndex);
allensCroftEntities1.DeleteObject(ObjectIndex);
Or use context declared in class scope instead of local one within Bookings_Loaded event handler by deleting that line:
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();

Entity Framework - Casting the retrieved Combobox value to string

Using Entity Framework, I have a Combobox showing a list of data retrieved from a database.
using System; //I removed the other using statements here to preserve space
namespace ExTea_BackEnd
{
public partial class frmAddBreakdown : Form
{
ExTeaEntities Breakdowns;
Breakdown_Type BreakdownTypes;
public frmAddBreakdown()
{
InitializeComponent();
}
private void cmbBreakdownType_SelectedIndexChanged(object sender, EventArgs e)
{
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
string selectedBreakdownTypeId = breakdownType.BrkdwnId;
IQueryable<Breakdown_Type> breakdownTypeQuery = from t in Breakdowns.Breakdown_Types
where t.BrkdwnId == selectedBreakdownTypeId
select t;
List<Breakdown_Type> selectedBreakdownId = breakdownTypeQuery.ToList();
if (selectedBreakdownId != null && selectedBreakdownId.Count > 0)
{
BreakdownTypes = selectedBreakdownId.First();
txtBreakdownId.Text = BreakdownTypes.BrkdwnId.ToString();
}
else
{
BreakdownTypes = null;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Breakdown newBreakdown = new Breakdown();
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
newBreakdown.BrkdwnType = breakdownType.ToString(); //this is where the error occurs
newBreakdown.MachineId = txtMachineId.Text.Trim();
newBreakdown.MachineType = txtMachineType.Text.Trim();
newBreakdown.ReportedDate = dtpDate.Value;
newBreakdown.JobStatus = "I";
Breakdowns.AddToBreakdowns(newBreakdown);
int rowsAffected = Breakdowns.SaveChanges();
if (rowsAffected > 0)
{
MessageBox.Show(rowsAffected + " records added!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! " + ex.Message);
}
}
}
}
I'm trying to save the data in the form back to the database, an error occurs when trying to cast the value selected from the Combobox. Even when I've casted it to the right type, it does not save the selected value! But this,
I'm clueless on what I'm doing wrong here? Can anyone please tell me how to correct this?
Thank you.
newBreakdown.BrkdwnType = breakdownType.ToString();
Here you are just calling .ToString() Method of your object, so it is returning the Type Name, which you are able to view in database table record, for getting the BrkDwnType Property value you should change statement to
newBreakdown.BrkdwnType = breakdownType.BrkdwnType;
it should just be:
newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString();
no need for casting selectedItem if you just want the string value. From a design point of view, you should probably normalize your database and use an ID for breakDownType that references another table with BreakDown types.

Saving changes from a combobox in a database

I have a combobox and want to save the changes in the database.
What I want to do is if the combobox is selected and it is true it must run the code below. If it is false it must then skip the code and go further.
The code below is checking if the combobox is enabled. But when I'm compiling it's saying true when not selected
private void Log()
{
if (kaartburgerlijkestand.Enabled)
{
veranderingBurgelijkestaat();
}
}
The code below is saving the data in the database
private string veranderingBurgerlijkestaat()
{
string gebruiker = curMedewerker.Behandelnaam;
string bekeken = prodermaform.pKaart();
string tabblad = tabControl1.SelectedTab.Text;
string pat = CPatient.GeefPatientNaam(patient.Id);
string wijz = "Burgerlijkestaat: " + kaartBurgerlijkestand.Text;
CDb dcon = new CDb();
try
{
if (dcon.Open())
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.loggen(Gebruiker, Bekeken, Tabblad, Patientnaam, Wijziging, Datum) VALUES(#gebruiker, #bekeken, #tabblad, #pat, #wijz, #datum)", dcon.Conn);
cmd.Parameters.AddWithValue("#gebruiker", gebruiker);
cmd.Parameters.AddWithValue("#bekeken", bekeken);
cmd.Parameters.AddWithValue("#tabblad", tabblad);
cmd.Parameters.AddWithValue("#pat", pat);
cmd.Parameters.AddWithValue("#wijz", wijz);
cmd.Parameters.AddWithValue("#datum", DateTime.Now);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dcon.Close();
}
return wijz;
}
Could someone show me a example how to do it
I Found the solution
I have made a check
private void doCheck(object sender, EventArgs e)
{
cmbox = false;
if (kaartBurgerlijkestaat.Focused)
{
veranderingBurgerlijkestand();
}
cmbox = true;
}
Then I used the SelectedValueChanged Event
private void kaartBurgerlijkestand_SelectedValueChanged(object sender, EventArgs e)
{
if (cmbox)
doCheck(sender, e);
}
And it works fine.
I want to thank you all for helping me!
Add an Event Listener, the kaartburgerlijkestand.Enabled only check your combobox is enabled to select or not.
Add this line after your InitializeComponent(); line of Form.cs file
kaartburgerlijkestand.SelectedIndexChanged += new System.EventHandler
(this.kaartburgerlijkestand_SelectedIndexChanged);
Also add a function for above code :
private void kaartburgerlijkestand_SelectedIndexChanged(object sender, EventArgs e)
{
veranderingBurgelijkestand();
}

Categories