C# how do i insert a value into the databse using the textbox i update table.xam
ID: 3821913 • Letter: C
Question
C# how do i insert a value into the databse using the textbox i update table.xaml.. I will supply all of the code that im using and have already written please help below will be the current classes and code that i have in my project..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
namespace MyFinalGroupProject
{
public class clsDataAccess
{
/// <summary>
/// Connection string to the database.
/// </summary>
private string sConnectionString;
/// <summary>
/// Constructor that sets the connection string to the database
/// </summary>
public clsDataAccess()
{
sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source= " + Directory.GetCurrentDirectory() + "\Invoice.mdb";
}
/// <summary>
/// This method takes an SQL statment that is passed in and executes it. The resulting values
/// are returned in a DataSet. The number of rows returned from the query will be put into
/// the reference parameter iRetVal.
/// </summary>
/// <param name="sSQL">The SQL statement to be executed.</param>
/// <param name="iRetVal">Reference parameter that returns the number of selected rows.</param>
/// <returns>Returns a DataSet that contains the data from the SQL statement.</returns>
public DataSet ExecuteSQLStatement(string sSQL, ref int iRetVal)
{
try
{
//Create a new DataSet
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
//Open the connection to the database
conn.Open();
//Add the information for the SelectCommand using the SQL statement and the connection object
adapter.SelectCommand = new OleDbCommand(sSQL, conn);
adapter.SelectCommand.CommandTimeout = 0;
//Fill up the DataSet with data
adapter.Fill(ds);
}
}
//Set the number of values returned
iRetVal = ds.Tables[0].Rows.Count;
//return the DataSet
return ds;
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." + MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// This method takes an SQL statment that is passed in and executes it. The resulting single
/// value is returned.
/// </summary>
/// <param name="sSQL">The SQL statement to be executed.</param>
/// <returns>Returns a string from the scalar SQL statement.</returns>
public string ExecuteScalarSQL(string sSQL)
{
try
{
//Holds the return value
object obj;
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
//Open the connection to the database
conn.Open();
//Add the information for the SelectCommand using the SQL statement and the connection object
adapter.SelectCommand = new OleDbCommand(sSQL, conn);
adapter.SelectCommand.CommandTimeout = 0;
//Execute the scalar SQL statement
obj = adapter.SelectCommand.ExecuteScalar();
}
}
//See if the object is null
if (obj == null)
{
//Return a blank
return "";
}
else
{
//Return the value
return obj.ToString();
}
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." + MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// This method takes an SQL statment that is a non query and executes it.
/// </summary>
/// <param name="sSQL">The SQL statement to be executed.</param>
/// <returns>Returns the number of rows affected by the SQL statement.</returns>
public int ExecuteNonQuery(string sSQL)
{
try
{
//Number of rows affected
int iNumRows;
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
//Open the connection to the database
conn.Open();
//Add the information for the SelectCommand using the SQL statement and the connection object
OleDbCommand cmd = new OleDbCommand(sSQL, conn);
cmd.CommandTimeout = 0;
//Execute the non query SQL statement
iNumRows = cmd.ExecuteNonQuery();
}
//return the number of rows affected
return iNumRows;
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." + MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
}
}
.......................................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
namespace MyFinalGroupProject
{
public class clsitem_Manager////////////////////////////////////////////this class managers flights from the database
{
//clsDataAccess db;
clsDataAccess db = new clsDataAccess();
DataSet ds = new DataSet();
BindingList<clsItem> lstItems = new BindingList<clsItem>();
public int numberOfRecords;
public BindingList<clsItem> GetAllItemsFromDB()////////////////////////////////////////////This method will get all flights from the db, put each flight into a clsFlight object, add that object to the list, then return that list to the UI
{
//lstFlights = ////////This is a list of flights that represents all flights from the database
////////////////Steps for you to complete
string sSQL = clsSQL.GetAllItems_SQL();/////////////////////////Get SQL to get all flights
int iRet = 0;
//Execute the sSQL statement using the clsDataAccess class to get the flights into a dataset
ds = db.ExecuteSQLStatement(sSQL, ref iRet);
foreach (DataRow dr in ds.Tables[0].Rows)
{
lstItems.Add(new clsItem { ItemCode = dr[0].ToString(), ItemDesc = dr[1].ToString(), Cost = dr[2].ToString() });
numberOfRecords++;
}
return lstItems;
}
//public void insert1()
//{
// foreach (DataRow row in ds.Rows)
// {
// if (row["IsActive"].ToString() == "Y")
// {
// numberOfRecords++;
// }
// }
//}
//public BindingList<clsItem> Insert()////////////////////////////////////////////This method will get all flights from the db, put each flight into a clsFlight object, add that object to the list, then return that list to the UI
//{
// //lstFlights = ////////This is a list of flights that represents all flights from the database
// ////////////////Steps for you to complete
// string sSQL = clsSQL.Insert();/////////////////////////Get SQL to get all flights
// int iRet = 0;
// //Execute the sSQL statement using the clsDataAccess class to get the flights into a dataset
// ds = db.ExecuteSQLStatement(sSQL, ref iRet);
// foreach (DataRow dr in ds.Tables[0].Rows)
// {
// lstItems.Add(new clsItem { ItemCode = dr[0].ToString(), ItemDesc = dr[1].ToString(), Cost = dr[2].ToString() });
// }
// return lstItems;
//}
}
public class clsItem
{
public string ItemCode { get; set; }
public string ItemDesc { get; set; }
public string Cost { get; set; }
}
}
................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyFinalGroupProject
{
public class clsSQL
{
public static string GetAllItems_SQL()
{
string sSQL;
sSQL = "Select ItemCode, ItemDesc, Cost FROM ItemDesc";
return sSQL;
}
public static string Insert()
{
string sSQL;
sSQL = "INSERT INTO ItemDesc(ItemCode, ItemDesc, Cost)" + "VALUES( 0 , 1 , 2)";
return sSQL;
}
}
}
----------------------------------------------------------------------
<Window x:Class="MyFinalGroupProject.UpdateTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="UpdateTable" Height="400" Width="800.86">
<Grid>
<DataGrid HorizontalAlignment="Center" Name="dataGrid1"
AutoGenerateColumns="False"
CanUserResizeRows="True"
CanUserResizeColumns="True"
CanUserReorderColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=ItemCode}" Header="Item Code" MaxWidth="200" />
<DataGridTextColumn Binding="{Binding Path=ItemDesc}" Header="Description" MaxWidth="600" />
<DataGridTextColumn Binding="{Binding Path=Cost}" Header="Cost" MaxWidth="300" />
</DataGrid.Columns>
</DataGrid>
<Label Content="Item Code:" HorizontalAlignment="Left" Margin="10,29,0,0" VerticalAlignment="Top"/>
<Label Content="Item Code:" HorizontalAlignment="Left" Margin="10,29,0,0" VerticalAlignment="Top"/>
<Label Content="Description:" HorizontalAlignment="Left" Margin="10,71,0,0" VerticalAlignment="Top"/>
<Label Content="Cost:" HorizontalAlignment="Left" Margin="19,118,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="TextBoxItem" HorizontalAlignment="Left" Height="23" Margin="112,29,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="TextBocDescription" HorizontalAlignment="Left" Height="23" Margin="112,73,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="TextBoxCost" HorizontalAlignment="Left" Height="23" Margin="112,119,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button x:Name="ButtonInsert" Content="Insert" HorizontalAlignment="Left" Margin="10,180,0,0" VerticalAlignment="Top" Width="75" Click="ButtonInsert_Click"/>
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
<Button x:Name="ButtonUpdate" Content="Update" HorizontalAlignment="Left" Margin="112,180,0,0" VerticalAlignment="Top" Width="75"/>
<Button x:Name="buttonDelete" Content="Delete" HorizontalAlignment="Left" Margin="214,180,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.56,-1.274"/>
</Grid>
</Window>
-----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Data.OleDb;
using System.IO;
using System.Configuration;
namespace MyFinalGroupProject
{
/// <summary>
/// Interaction logic for UpdateTable.xaml
/// </summary>
public partial class UpdateTable : Window
{
/// <summary>
/// Used to Access the Database
/// </summary>
//clsDataAccess db;
//BindingList<clsItem> lstItems;
clsitem_Manager item;
// clsItem items;
//OleDbConnection con;
//DataTable dt;
public UpdateTable()
{
InitializeComponent();
item = new clsitem_Manager();
dataGrid1.ItemsSource = item.GetAllItemsFromDB();
}
private void ButtonInsert_Click(object sender, RoutedEventArgs e)
{
TextBoxItem.Text = item.numberOfRecords.ToString();
// item.insert1();
//dataGrid1.ItemsSource = item.GetAllItemsFromDB();
}
}
}
Explanation / Answer
class myclass
{
#region decleratons
public string username { get;set;}
public string password { get; set; }
public string error { get; set; }
#endregion
#region methods
public void insert()
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["constr"]);
SqlCommand cmd = new SqlCommand("spinsert", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter puname = new SqlParameter("@username", SqlDbType.VarChar, 50);
SqlParameter ppass = new SqlParameter("@password", SqlDbType.VarChar, 50);
puname.Value = username;
ppass.Value = password;
cmd.Parameters.Add(puname);
cmd.Parameters.Add(ppass);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
error = ex.ToString();
}
finally
{
cmd.Dispose();
con.Close();
}
}
#endregion
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.