这是用于将数据插入数据网格的函数。我也有不同的代码用于单击按钮以查看datagridview中的数据。我正在使用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 ");
}
}
以下代码用于在datgrid中加载数据的按钮
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);
}
答案 0 :(得分:0)
SELECT @@IDENTITY;
完成INSERT,SELECT INTO或批量复制语句后, @@ IDENTITY包含由...生成的最后一个标识值 言。