这是一个函数,用于获取要插入到数据集中的数据。我也有不同的代码按钮点击查看数据的数据。我使用sql server 2014作为我的数据库,并且在创建该表时已经设置了自动增量。自动递增的值是项id。
public: bool AddSuppliesToTable(Supplies^ rowtosave, SqlConnection^conn,
SqlCommand^ cmd)
{
Trace::WriteLine("saving to table");
cmd->Connection = conn;
cmd->CommandText = "SET IDENTITY_INSERT Supplies ON";
cmd->CommandText = "Insert Into Supplies (item_id, product_name,
stock_amnt,price,item_category) values(@item_id, @product_name,
@stock_amnt,@price,@item_category);";
cmd->CommandText = "SET IDENTITY_INSERT Supplies OFF";
cmd->Parameters->Add("@item_id",rowtosave->getId());
cmd->Parameters->Add("@product_name", rowtosave->getProductNAme());
cmd->Parameters->Add("@stock_amnt", rowtosave->getStockAmount());
cmd->Parameters->Add("@price", rowtosave->getPrice());
cmd->Parameters->Add("@item_category", rowtosave->getItemCategory());
cmd->ExecuteReader();
return true;
}这是datagridview的函数。
private: System::Void loadtablebutton_Click(System::Object^ sender,
System::EventArgs^ e)
{
String^ sCon = "Data Source=Chevy; Initial Catalog=Ulti-Stocks;
Integrated Security = true";
SqlConnection^ conn = gcnew SqlConnection(sCon);
SqlCommand^ cmd = gcnew SqlCommand();
cmd->Connection = conn;
cmd->CommandText = "Select *from Supplies";
try{
SqlDataAdapter^ sda = gcnew SqlDataAdapter();
sda->SelectCommand = cmd;
DataTable^ dt = gcnew DataTable();
sda->Fill(dt);
BindingSource^ bsource = gcnew BindingSource();
bsource->DataSource = dt;
dataGridView1->DataSource = bsource;
sda->Update(dt);
MessageBox::Show("Loading Table Data was successful");
}
catch (Exception^ ex)
{
MessageBox::Show(" Error loading data ");
}
}下面的代码是一个按钮来加载数据网格中的数据。
private: System::Void button1_Click(System::Object^ sender,
System::EventArgs^ e)
{
UltiStocks::Supplies^ supplies = gcnew UltiStocks::Supplies();
int id, stock;
float price;
try{
supplies->setItemId(id = Convert::ToInt32(Text));
supplies->setProductName(itemnametextbox->Text);
supplies->setStockAmount(stock =
Convert::ToInt32(stockamnttextBox->Text));
supplies->setPrice(price = Convert::ToSingle(pricetextBox-
>Text));
supplies->setItemCategory(categorytextBox->Text);
UltiStocks::DataBase^ database = gcnew
UltiStocks::DataBase();
database->OpenConnection();
database->AddItemtable(supplies);
database->CloseConnection();
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}发布于 2015-03-09 06:43:52
SELECT @@IDENTITY;
在完成INSERT、SELECT INTO或批量复制语句之后,@@IDENTITY包含语句生成的最后一个标识值。
https://stackoverflow.com/questions/28936265
复制相似问题