설명 없음
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Frm_01_finish_rcp.vb 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. Imports System.Data.SqlClient
  2. Imports System.IO
  3. Imports NPOI.XSSF.UserModel
  4. Imports NPOI.SS.UserModel
  5. Public Class Frm_01_finish_rcp
  6. Private isFlashing As Boolean = False
  7. Dim cmd As New SqlCommand
  8. Dim da As New SqlDataAdapter
  9. Dim sql As String
  10. Dim colorArray(10) As Color
  11. Dim conn As New SqlConnection
  12. Private Sub SetupAutoCompleteForCustomer()
  13. Dim customerList As New AutoCompleteStringCollection() : customerList.AddRange(New String() {"客戶A", "客戶B", "客戶C", "客戶D"}) ' 可從數據庫加載
  14. cbo_customer.AutoCompleteMode = AutoCompleteMode.SuggestAppend : cbo_customer.AutoCompleteSource = AutoCompleteSource.CustomSource
  15. cbo_customer.AutoCompleteCustomSource = customerList
  16. End Sub
  17. Private Sub SetupAutoCompleteForColor()
  18. Dim colorList As New AutoCompleteStringCollection() : colorList.AddRange(New String() {"紅色", "藍色", "綠色", "黑色", "白色"}) ' 可從數據庫加載
  19. txtColor.AutoCompleteMode = AutoCompleteMode.SuggestAppend : txtColor.AutoCompleteSource = AutoCompleteSource.CustomSource
  20. txtColor.AutoCompleteCustomSource = colorList
  21. End Sub
  22. Private Sub Set_清單1(條件 As String)
  23. Dim ds1 As New DataSet
  24. 處方清單_dgv.DataSource = Nothing : ds1.Clear()
  25. 處方清單_dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
  26. 處方清單_dgv.ColumnHeadersHeight = 30 : 處方清單_dgv.AllowUserToAddRows = False : 處方清單_dgv.RowTemplate.Height = 20
  27. 處方清單_dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
  28. SQL_塗飾處方清單(條件)
  29. da.Fill(ds1) : 處方清單_dgv.DataSource = ds1.Tables(0) : conn.Close()
  30. 處方清單_dgv.Columns(0).FillWeight = 200
  31. For i As Integer = 0 To 處方清單_dgv.Columns.Count - 1 : 處方清單_dgv.Columns(i).ReadOnly = True : Next
  32. End Sub
  33. Private Sub Frm_01_finish_rcp_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  34. Me.MdiParent = FrmMDI : Me.WindowState = 2 : Me.AutoScroll = True
  35. Set_清單1("")
  36. Timer1.Interval = 1000 ' 每 500 毫秒闪烁一次
  37. txtCustomer.AutoCompleteMode = AutoCompleteMode.SuggestAppend : txtCustomer.AutoCompleteSource = AutoCompleteSource.CustomSource
  38. SetupAutoCompleteForCustomer() : SetupAutoCompleteForColor()
  39. End Sub
  40. Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
  41. If isFlashing Then : 模式通知_lb.Text = "修改模式" : Else : 模式通知_lb.Text = "" : End If : isFlashing = Not isFlashing ' 切换闪烁状态
  42. End Sub
  43. Private Sub 處方清單_dgv_SelectionChanged(sender As Object, e As EventArgs) Handles 處方清單_dgv.SelectionChanged
  44. Dim ds1 As New DataSet
  45. 處方_dgv.DataSource = Nothing : ds1.Clear()
  46. 處方_dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
  47. 處方_dgv.ColumnHeadersHeight = 30 : 處方_dgv.AllowUserToAddRows = False : 處方_dgv.RowTemplate.Height = 25
  48. 處方_dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
  49. SQL_塗飾處方明細(處方清單_dgv.Rows(處方清單_dgv.CurrentCell.RowIndex).Cells(0).Value)
  50. da.Fill(ds1) : 處方_dgv.DataSource = ds1.Tables(0) : conn.Close()
  51. 處方_dgv.Columns(0).FillWeight = 220 : 處方_dgv.Columns(2).FillWeight = 180
  52. For i As Integer = 0 To 處方_dgv.Columns.Count - 1 : 處方_dgv.Columns(i).ReadOnly = True : Next
  53. For Each row As DataGridViewRow In 處方_dgv.Rows : For Each cell As DataGridViewCell In row.Cells : cell.Tag = cell.Value : Next : Next
  54. End Sub
  55. Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles 關鍵字_tb.TextChanged
  56. Set_清單1("WHERE rcp_name LIKE N'%" & 關鍵字_tb.Text & "%'")
  57. End Sub
  58. Private Sub 處方_dgv_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles 處方_dgv.CellPainting
  59. If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then ' 自定义单元格绘制,确保字体位置居中,并选中单元格背景色为蓝色
  60. Dim cell As DataGridViewCell = 處方_dgv.Rows(e.RowIndex).Cells(e.ColumnIndex)
  61. If cell.Style.ForeColor = Color.Red OrElse e.State.HasFlag(DataGridViewElementStates.Selected) Then ' 判断是否需要自定义绘制
  62. Dim backgroundColor As Color = If(e.State.HasFlag(DataGridViewElementStates.Selected), ' 获取背景颜色
  63. e.CellStyle.SelectionBackColor, e.CellStyle.BackColor)
  64. e.Graphics.FillRectangle(New SolidBrush(backgroundColor), e.CellBounds) ' 填充背景色
  65. e.Paint(e.ClipBounds, DataGridViewPaintParts.Border) ' 使用默认的边框样式绘制边框
  66. Dim textFormat As TextFormatFlags = TextFormatFlags.VerticalCenter ' 根据单元格的对齐方式调整文本绘制位置
  67. If e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then : textFormat = textFormat Or TextFormatFlags.Right
  68. ElseIf e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter Then : textFormat = textFormat Or TextFormatFlags.HorizontalCenter
  69. Else : textFormat = textFormat Or TextFormatFlags.Left : End If ' 绘制文本内容
  70. TextRenderer.DrawText(e.Graphics, cell.Value?.ToString(), e.CellStyle.Font, e.CellBounds, cell.Style.ForeColor, textFormat)
  71. e.Handled = True ' 阻止默认绘制
  72. End If
  73. End If
  74. End Sub
  75. Private Sub 處方_dgv_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles 處方_dgv.CellValueChanged
  76. Dim currentCell As DataGridViewCell = 處方_dgv.Rows(e.RowIndex).Cells(e.ColumnIndex) ' 获取修改的单元格
  77. If currentCell.Tag IsNot Nothing AndAlso Not currentCell.Value.Equals(currentCell.Tag) Then ' 检查 Tag 是否存在,以及当前值是否与原值不同
  78. currentCell.Style.ForeColor = Color.Red ' 如果值被修改,将字体设置为红色
  79. Else
  80. currentCell.Style.ForeColor = Color.Black ' 如果值未修改,恢复默认字体颜色
  81. End If
  82. End Sub
  83. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
  84. ' 启用 Label1
  85. 模式通知_lb.Enabled = True
  86. ' 启动 Timer1
  87. Timer1.Start()
  88. ' 确保当前 DataGridView 的焦点单元格有效
  89. Dim currentCell As DataGridViewCell = 處方_dgv.CurrentCell
  90. If currentCell Is Nothing Then
  91. MessageBox.Show("请选中一个单元格进行编辑。")
  92. Return
  93. End If
  94. ' 获取当前选中行的第 0 列和第 2 列的值
  95. Dim sysName As String = 處方_dgv.CurrentRow.Cells(0).Value.ToString() ' 化学品名称
  96. Dim qty As String = 處方_dgv.CurrentRow.Cells(2).Value.ToString() ' 份数
  97. ' 从数据库获取化学品名称作为自动完成数据
  98. Dim suggestions As List(Of String) = ChemicalNamesFromDatabase()
  99. ' 初始化并显示 AutoCompleteInputBox,传入从数据库获取的建议列表
  100. Dim inputBox As New AutoCompleteWithListBox("输入化学品名称", suggestions, sysName, qty)
  101. Dim my_input() As String
  102. If inputBox.ShowDialog() = DialogResult.OK Then
  103. my_input = Split(inputBox.UserInput, " ")
  104. ' Dim chemName = inputBox.UserInput
  105. ' 显示结果
  106. MessageBox.Show($"选择的化学品:{my_input(1)}{vbNewLine}数量:{inputBox.Quantity}")
  107. End If
  108. Dim chemName = my_input(1)
  109. Dim re_qty = inputBox.Quantity
  110. ' 更新 DataGridView 的单元格信息
  111. If inputBox.DialogResult = DialogResult.OK Then
  112. ' 判断化学品名称是否被修改
  113. If sysName <> chemName Then
  114. 處方_dgv.CurrentRow.Cells("化工品名").Value = my_input(1) ' 更新化学品名称
  115. 處方_dgv.CurrentRow.Cells("化工品名").Style.ForeColor = Color.Red ' 设置化学品名称为红色字体
  116. ' 查询化工分类并更新
  117. Dim type1 As String = GetChemicalTypesFromDatabase(my_input(1))
  118. 處方_dgv.CurrentRow.Cells("化工分类").Value = type1 ' 更新化工分类
  119. End If
  120. ' 判断份数是否被修改
  121. If qty <> inputBox.Quantity Then
  122. 處方_dgv.CurrentRow.Cells("份数").Value = re_qty ' 更新份数
  123. 處方_dgv.CurrentRow.Cells("份数").Style.ForeColor = Color.Red ' 设置份数为红色字体
  124. End If
  125. End If
  126. End Sub
  127. Private Function GetChemicalTypesFromDatabase(chemicalName As String) As String
  128. ' 数据库连接字符串
  129. Dim connectionString As String = connstring ' 请替换为你的实际数据库连接字符串
  130. ' 查询语句
  131. Dim query As String = "SELECT type FROM ht_k3_material WHERE name = @sys_name"
  132. Dim type1 As String = ""
  133. ' 使用 SQL 连接和命令
  134. Using connection As New SqlConnection(connectionString)
  135. Dim command As New SqlCommand(query, connection)
  136. ' 添加查询参数
  137. command.Parameters.AddWithValue("@sys_name", chemicalName)
  138. ' 打开数据库连接
  139. connection.Open()
  140. ' 执行查询并获取结果
  141. Dim result = command.ExecuteScalar()
  142. If result IsNot Nothing Then
  143. type1 = result.ToString() ' 确保返回类型为字符串
  144. End If
  145. End Using
  146. ' 返回化工分类
  147. Return type1
  148. End Function
  149. ' 原本返回的是 String(),现在改为 List(Of String)
  150. Private Function ChemicalNamesFromDatabase() As List(Of String)
  151. Dim connectionString As String = connstring ' 换成你的数据库连接字符串
  152. Dim query As String = "SELECT code,name FROM ht_k3_material"
  153. Dim chemicalNames As New List(Of String)()
  154. Using connection As New SqlConnection(connectionString)
  155. Using command As New SqlCommand(query, connection)
  156. connection.Open()
  157. Using reader As SqlDataReader = command.ExecuteReader()
  158. While reader.Read()
  159. ' 将 sys_name 添加到列表中
  160. chemicalNames.Add(reader("code").ToString() & " " & reader("name").ToString())
  161. End While
  162. End Using
  163. End Using
  164. End Using
  165. ' 返回 List(Of String)
  166. Return chemicalNames
  167. End Function
  168. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnSave.Click
  169. ' 數據庫連接字串
  170. Dim connectionString As String = connstring ' 確保你的連接字符串正確
  171. ' **(A) 取得選中的 rcp_name**
  172. If 處方清單_dgv.CurrentRow Is Nothing OrElse 處方清單_dgv.CurrentRow.Cells("配料名称").Value Is Nothing Then
  173. MessageBox.Show("請先選擇一個配料名称 (rcp_name)!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  174. Return
  175. End If
  176. Dim rcpName As String = 處方清單_dgv.CurrentRow.Cells("配料名称").Value.ToString()
  177. ' **(B) 確保 dgv2 內有數據**
  178. If 處方_dgv.Rows.Count = 0 Then
  179. MessageBox.Show("沒有數據可更新!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
  180. Return
  181. End If
  182. ' **(C) 記錄目前選中的行**
  183. Dim selectedRowIndex As Integer = 處方_dgv.CurrentCell.RowIndex
  184. Dim selectedId As String = If(處方_dgv.CurrentRow.Cells("id").Value IsNot Nothing, 處方_dgv.CurrentRow.Cells("id").Value.ToString(), "")
  185. ' **(D) 開始 SQL Transaction**
  186. Using conn As New SqlConnection(connectionString)
  187. conn.Open()
  188. Using trans As SqlTransaction = conn.BeginTransaction()
  189. Try
  190. ' **(E) 刪除資料表中該 rcp_name 的所有數據**
  191. Dim deleteQuery As String = "DELETE FROM ht_finish_rcp WHERE rcp_name = @rcp_name;"
  192. Using cmd As New SqlCommand(deleteQuery, conn, trans)
  193. cmd.Parameters.AddWithValue("@rcp_name", rcpName)
  194. cmd.ExecuteNonQuery()
  195. End Using
  196. ' **(F) 遍歷 dgv2,將沒有刪除線的數據重新插入**
  197. Dim insertQuery As String = "INSERT INTO ht_finish_rcp (id, rcp_name, chem_name, percents, edited_date)
  198. VALUES (@id, @rcp_name, @chem_name, @percents, @edited_date);"
  199. For Each row As DataGridViewRow In 處方_dgv.Rows
  200. ' 確保不是空白行
  201. If row.IsNewRow Then Continue For
  202. ' **(G) 檢查是否有刪除線 (Strikeout)**
  203. Dim hasStrikeout As Boolean = False
  204. For Each cell As DataGridViewCell In row.Cells
  205. If cell.Style.Font IsNot Nothing AndAlso cell.Style.Font.Strikeout Then
  206. hasStrikeout = True
  207. Exit For
  208. End If
  209. Next
  210. If hasStrikeout Then
  211. Debug.Print("跳過刪除線記錄:" & row.Cells("化工品名").Value.ToString()) ' Debug 記錄
  212. Continue For ' **跳過刪除線的記錄,不插入數據庫**
  213. End If
  214. ' 取得數據
  215. Dim idString As String = If(row.Cells("id").Value IsNot Nothing, row.Cells("id").Value.ToString(), "")
  216. If String.IsNullOrEmpty(idString) Then Continue For ' 跳過無效數據
  217. Dim chemName As String = row.Cells("化工品名").Value.ToString()
  218. Dim percents As String = row.Cells("份数").Value.ToString()
  219. Dim dPercents As Decimal = 0
  220. Decimal.TryParse(percents, dPercents)
  221. ' **(H) 插入新數據**
  222. Using cmd As New SqlCommand(insertQuery, conn, trans)
  223. cmd.Parameters.AddWithValue("@id", idString)
  224. cmd.Parameters.AddWithValue("@rcp_name", rcpName)
  225. cmd.Parameters.AddWithValue("@chem_name", chemName)
  226. cmd.Parameters.AddWithValue("@percents", dPercents)
  227. cmd.Parameters.AddWithValue("@edited_date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
  228. cmd.ExecuteNonQuery()
  229. End Using
  230. Next
  231. ' **(I) 提交 Transaction**
  232. trans.Commit()
  233. MessageBox.Show("所有數據已成功同步至資料庫!", "更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information)
  234. ' **(J) 重新載入 dgv2 的資料**
  235. ReloadDGV2(rcpName)
  236. ' **(K) 恢復選取的 row**
  237. RestoreSelectedRow(selectedRowIndex, selectedId)
  238. Catch ex As Exception
  239. ' **(L) 出錯時回滾**
  240. trans.Rollback()
  241. MessageBox.Show("更新失敗:" & ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
  242. End Try
  243. End Using
  244. End Using
  245. End Sub
  246. Private Sub RestoreSelectedRow(previousRowIndex As Integer, previousId As String)
  247. ' **確保 dgv2 內有數據**
  248. If 處方_dgv.Rows.Count = 0 Then Return
  249. ' **嘗試選擇原來的行**
  250. For Each row As DataGridViewRow In 處方_dgv.Rows
  251. If row.Cells("id").Value IsNot Nothing AndAlso row.Cells("id").Value.ToString() = previousId Then
  252. 處方_dgv.CurrentCell = row.Cells(0)
  253. row.Selected = True
  254. Return
  255. End If
  256. Next
  257. ' **如果原行被刪除,則選擇前一行**
  258. Dim newRowIndex As Integer = previousRowIndex
  259. If newRowIndex >= 處方_dgv.Rows.Count Then
  260. newRowIndex = 處方_dgv.Rows.Count - 1 ' 如果超過範圍,則選擇最後一行
  261. End If
  262. If newRowIndex >= 0 Then
  263. 處方_dgv.CurrentCell = 處方_dgv.Rows(newRowIndex).Cells(0)
  264. 處方_dgv.Rows(newRowIndex).Selected = True
  265. End If
  266. End Sub
  267. Private Sub ReloadDGV2(rcpName As String)
  268. ' **SQL 查詢 rcp_name 的新數據**
  269. Dim query As String = "SELECT chem_name AS 化工品名, percents as 份数,id, EDITED_DATE FROM ht_finish_rcp WHERE rcp_name = @rcp_name"
  270. Dim connectionString As String = connstring
  271. Dim adapter As New SqlDataAdapter(query, connectionString)
  272. adapter.SelectCommand.Parameters.AddWithValue("@rcp_name", rcpName)
  273. Dim dt As New DataTable()
  274. adapter.Fill(dt)
  275. ' **重新綁定 DataGridView**
  276. 處方_dgv.DataSource = dt
  277. 處方_dgv.Columns(0).Width = 220
  278. 處方_dgv.Columns(2).Width = 220
  279. End Sub
  280. ''' <summary>
  281. ''' 小工具:安全取得某欄位字串;如果是 Nothing 則回傳 ""
  282. ''' </summary>
  283. Private Function SafeCellValue(row As DataGridViewRow, columnName As String) As String
  284. If row.Cells(columnName).Value IsNot Nothing Then
  285. Return row.Cells(columnName).Value.ToString().Trim()
  286. End If
  287. Return String.Empty
  288. End Function
  289. Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
  290. 關鍵字_tb.Enabled = False
  291. 'For Each cell As DataGridViewCell In dgv2.CurrentRow.Cells
  292. ' ' 将单元格的值恢复为 Tag 中存储的原始值
  293. ' cell.Value = cell.Tag
  294. ' ' 将字体颜色恢复为默认黑色
  295. ' cell.Style.ForeColor = Color.Black
  296. 'Next
  297. Try
  298. ' **檢查 DataGridView 是否有未保存的變更**
  299. If 處方_dgv IsNot Nothing AndAlso 處方_dgv.DataSource IsNot Nothing Then
  300. Dim dt As DataTable = CType(處方_dgv.DataSource, DataTable)
  301. ' **取消所有變更**
  302. dt.RejectChanges()
  303. End If
  304. ' **清除選取**
  305. 處方_dgv.ClearSelection()
  306. ' **隱藏 DataGridView 的空白行**
  307. 處方_dgv.AllowUserToAddRows = False
  308. ' **確保數值欄位不為 null**
  309. For Each row As DataGridViewRow In 處方_dgv.Rows
  310. If Not row.IsNewRow Then ' 避免影響新行
  311. For Each cell As DataGridViewCell In row.Cells
  312. ' **如果是數值欄位,將 null 設為 0**
  313. If IsDBNull(cell.Value) AndAlso IsNumeric(cell.OwningColumn.DataPropertyName) Then
  314. cell.Value = 0
  315. End If
  316. Next
  317. End If
  318. Next
  319. Catch ex As Exception
  320. MessageBox.Show("取消變更時發生錯誤:" & ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
  321. End Try
  322. End Sub
  323. Private Sub dgv2_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles 處方_dgv.DataError
  324. ' **防止 "無法將 null 設定給 DataGridView" 錯誤**
  325. If e.Exception IsNot Nothing Then
  326. MessageBox.Show("數據錯誤:" & e.Exception.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  327. ' **只修正數值欄位,避免影響文字欄位**
  328. Try
  329. Dim columnName As String = 處方_dgv.Columns(e.ColumnIndex).DataPropertyName
  330. If IsNumeric(columnName) Then
  331. 處方_dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0 ' 設為 0,避免錯誤
  332. Else
  333. 處方_dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = DBNull.Value ' 保持空值
  334. End If
  335. Catch ex As Exception
  336. Debug.Print("無法修正 DataGridView 錯誤:" & ex.Message)
  337. End Try
  338. End If
  339. End Sub
  340. Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
  341. If 處方_dgv.CurrentRow IsNot Nothing Then
  342. For Each cell As DataGridViewCell In 處方_dgv.CurrentRow.Cells
  343. ' 设置字体为带删除线的样式
  344. Dim currentFont As Font = cell.Style.Font
  345. If currentFont Is Nothing Then
  346. currentFont = 處方_dgv.Font ' 使用默认字体
  347. End If
  348. cell.Style.Font = New Font(currentFont, FontStyle.Strikeout)
  349. ' 设置背景颜色为红色
  350. cell.Style.BackColor = Color.Red
  351. Next
  352. End If
  353. End Sub
  354. Private Function GetNewIDWithIncrement() As Decimal
  355. ' 如果 dgv2 为空,则返回 1 作为第一行的 ID
  356. If 處方_dgv.Rows.Count = 0 Then Return 1D
  357. Dim selectedIndex As Integer = 處方_dgv.CurrentRow.Index
  358. Dim currentID As Decimal = Convert.ToDecimal(處方_dgv.Rows(selectedIndex).Cells("id").Value)
  359. ' 如果选中的是最后一行,直接加 1
  360. If selectedIndex = 處方_dgv.Rows.Count - 1 Then
  361. Return currentID + 1D
  362. End If
  363. ' 否则,在当前选中行后插入新记录,新 ID = 当前行 ID + 0.1
  364. Return currentID + 0.1D
  365. End Function
  366. Private Sub Button5_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
  367. ' 1️⃣ 获取 DataGridView 绑定的 DataTable
  368. Dim dt As DataTable = CType(處方_dgv.DataSource, DataTable)
  369. ' 2️⃣ 获取新 ID(当前选中行 ID + 0.1)
  370. Dim newID As Decimal = GetNewIDWithIncrement()
  371. ' 3️⃣ 读取数据库中的化工品建议列表
  372. Dim suggestions As List(Of String) = ChemicalNamesFromDatabase().ToList()
  373. ' 4️⃣ 打开输入框,用户输入化工品名和数量
  374. Dim inputBox As New AutoCompleteWithListBox("输入化学品名称", suggestions, "", "0")
  375. Dim my_input() As String
  376. If inputBox.ShowDialog() = DialogResult.OK Then
  377. ' 5️⃣ 读取用户输入
  378. my_input = Split(inputBox.UserInput, " ")
  379. Dim chemName As String = my_input(1)
  380. Dim qty As String = inputBox.Quantity
  381. Dim type1 As String = GetChemicalTypesFromDatabase(chemName)
  382. ' 🚨 份数不可为 0,弹出警告并返回 🚨
  383. If String.IsNullOrWhiteSpace(qty) OrElse Not IsNumeric(qty) OrElse Convert.ToDecimal(qty) = 0 Then
  384. MessageBox.Show("份数不可为 0,请输入正确的数量!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
  385. Return ' 直接退出,不执行插入
  386. End If
  387. ' 6️⃣ 在 DataTable 中插入新行
  388. Dim newRow As DataRow = dt.NewRow()
  389. newRow("化工品名") = chemName
  390. newRow("份数") = qty
  391. newRow("化工分类") = type1
  392. newRow("id") = newID ' ID 采用小数递增
  393. ' 檢查 DataTable 是否已經有 "Status" 欄位,沒有則新增
  394. If Not dt.Columns.Contains("Status") Then
  395. dt.Columns.Add("Status", GetType(String)) ' 新增一個 "Status" 欄位,型別為 String
  396. End If
  397. ' **新增数据,标记为 "NEW"**
  398. newRow("Status") = "NEW" ' 这里添加一个新列 "Status" 作为标记
  399. ' 7️⃣ 插入新行到选中行的下一行
  400. dt.Rows.InsertAt(newRow, 處方_dgv.CurrentRow.Index + 1)
  401. ' 8️⃣ 重新绑定 DataGridView
  402. 處方_dgv.DataSource = dt
  403. ' 9️⃣ 设置新行的字体颜色为红色,表示未保存
  404. For Each cell As DataGridViewCell In 處方_dgv.Rows(處方_dgv.CurrentRow.Index + 1).Cells
  405. cell.Style.ForeColor = Color.Red
  406. Next
  407. End If
  408. End Sub
  409. Private Sub Button6_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
  410. Dim my_list As String
  411. For Each row As DataGridViewRow In 處方_dgv.Rows
  412. If row.Cells("化工分类").Value.ToString = "" And Not (row.Cells("化工品名").Value Like "水*") Then
  413. my_list += row.Cells("化工品名").Value & vbNewLine
  414. End If
  415. Next
  416. If Microsoft.VisualBasic.Len(my_list) > 0 Then
  417. MsgBox("以下化工品名有误:" & vbNewLine & vbNewLine & my_list)
  418. Exit Sub
  419. End If
  420. ' **(1) 請使用者輸入泡料總重量**
  421. Dim totalWeightStr As String = InputBox("请输入配料的总重量 (kg):", "输入总重量")
  422. Dim totalWeight As Decimal
  423. ' **(2) 檢查輸入是否合法**
  424. If Not Decimal.TryParse(totalWeightStr, totalWeight) OrElse totalWeight <= 0 Then
  425. MessageBox.Show("請输入有效的总重量!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  426. Return
  427. End If
  428. ' **(3) 計算總份數**
  429. Dim totalPortions As Decimal = 0
  430. For Each row As DataGridViewRow In 處方_dgv.Rows
  431. If row.IsNewRow Then Continue For ' 跳過新行
  432. Dim portionStr As String = row.Cells("份数").Value.ToString()
  433. Dim portion As Decimal = 0
  434. If Decimal.TryParse(portionStr, portion) Then
  435. totalPortions += portion
  436. End If
  437. Next
  438. ' **(4) 確保份數不為 0**
  439. If totalPortions = 0 Then
  440. MessageBox.Show("化工品的總份數為 0,無法計算重量!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  441. Return
  442. End If
  443. ' **(5) 清空 dgv3 並填充新數據**
  444. Dim dt As New DataTable()
  445. dt.Columns.Add("化工品名", GetType(String))
  446. dt.Columns.Add("化工分类", GetType(String))
  447. dt.Columns.Add("份数", GetType(Decimal))
  448. dt.Columns.Add("重量 (kg)", GetType(Decimal))
  449. dt.Columns.Add("总重量 (kg)", GetType(Decimal))
  450. dt.Columns.Add("化工代码", GetType(String))
  451. ' **(6) 計算每個化工的重量並填入 dgv3**
  452. Dim totalCalculatedWeight As Decimal = 0
  453. For Each row As DataGridViewRow In 處方_dgv.Rows
  454. If row.IsNewRow Then Continue For
  455. Dim chemName As String = row.Cells("化工品名").Value.ToString()
  456. Dim chemCategory As String = row.Cells("化工分类").Value.ToString()
  457. Dim portion As Decimal = Convert.ToDecimal(row.Cells("份数").Value)
  458. ' 計算該化工品的重量
  459. Dim weight As Decimal = Math.Round((portion / totalPortions) * totalWeight, 1)
  460. totalCalculatedWeight += weight ' 累計總重量
  461. ' **(7) 加入 DataTable**
  462. dt.Rows.Add(chemName, chemCategory, portion, weight, totalWeight)
  463. Next
  464. ' **(8) 添加總計行**
  465. Dim totalRow As DataRow = dt.NewRow()
  466. totalRow("化工品名") = "总计"
  467. totalRow("化工分类") = ""
  468. totalRow("份数") = totalPortions
  469. totalRow("重量 (kg)") = totalCalculatedWeight
  470. totalRow("总重量 (kg)") = totalWeight
  471. dt.Rows.Add(totalRow)
  472. ' **(9) 更新 dgv3**
  473. DGV3.DataSource = dt
  474. ' **(3) 設定總計行樣式(紅色粗體)**
  475. Dim lastRowIndex As Integer = DGV3.Rows.Count - 1
  476. If lastRowIndex >= 0 Then
  477. Dim lastRow As DataGridViewRow = DGV3.Rows(lastRowIndex)
  478. If lastRow.Cells(0).Value IsNot Nothing AndAlso lastRow.Cells(0).Value.ToString() = "总计" Then
  479. For Each cell As DataGridViewCell In lastRow.Cells
  480. cell.Style.Font = New Font("Microsoft YaHei", 10, FontStyle.Bold)
  481. cell.Style.ForeColor = Color.Red
  482. Next
  483. End If
  484. End If
  485. ' **(10) 美化 dgv3**
  486. ' CustomizeDataGridView(DGV3)
  487. End Sub
  488. Private Sub Button_領料_Click(sender As Object, e As EventArgs) Handles Button7.Click
  489. ' ------------------------ 1️⃣ 生成領料單號 ------------------------
  490. Dim out_Number As String = GenerateSerialNumber(DateTimePicker1.Value)
  491. ' ------------------------ 2️⃣ 計算總重量 ------------------------
  492. Dim totalWeight As Double = DGV3.Rows.Cast(Of DataGridViewRow)().
  493. Sum(Function(r) Convert.ToDouble(r.Cells(4).Value))
  494. totalWeight = Math.Round(totalWeight) ' 四捨五入取整
  495. ' ------------------------ 3️⃣ 讀取 Excel 模板 ------------------------
  496. Dim templatePath As String = "C:\表格模版\涂饰配料标签模版.xlsx"
  497. Dim savePath As String = Path.Combine("C:\GHS", out_Number & ".xlsx")
  498. Dim workbook As IWorkbook
  499. Using fs As New FileStream(templatePath, FileMode.Open, FileAccess.Read)
  500. workbook = New XSSFWorkbook(fs)
  501. End Using
  502. ' 假設我們要操作第 1 個工作表
  503. Dim sheet As ISheet = workbook.GetSheetAt(0)
  504. ' ------------------------ 4️⃣ 寫入 Excel ------------------------
  505. ' ========== (A) 設置 rcp_name 到 A1、B1 ==========
  506. ' 假設 DGV1.CurrentRow.Cells("配料名称") 有你想填入的值
  507. Dim rcpName As String = 處方清單_dgv.CurrentRow.Cells("配料名称").Value.ToString()
  508. ' 先確保第 1 行(索引0)已存在
  509. Dim row0 As IRow = sheet.GetRow(0)
  510. If row0 Is Nothing Then
  511. row0 = sheet.CreateRow(0)
  512. End If
  513. ' A1 => GetCell(0)
  514. Dim cellA1 As ICell = row0.GetCell(0)
  515. If cellA1 Is Nothing Then
  516. cellA1 = row0.CreateCell(0)
  517. End If
  518. cellA1.SetCellValue(rcpName)
  519. ' B1 => GetCell(1)
  520. Dim cellB1 As ICell = row0.GetCell(1)
  521. If cellB1 Is Nothing Then
  522. cellB1 = row0.CreateCell(1)
  523. End If
  524. cellB1.SetCellValue(rcpName)
  525. ' ========== (B) 成份明細 D2:D14 (化工品) & E2:E14 (重量) ==========
  526. ' 從 DGV3 把化工品名稱、重量 分別寫到 D、E 欄 (索引3, 4)
  527. ' 從 Excel 的第 2 行(索引1)開始,直到第 14 行(索引13)
  528. Dim startExcelRow As Integer = 1 ' D2 所在的行索引
  529. Dim endExcelRow As Integer = 15 ' D14 所在的行索引
  530. Dim rowIndex As Integer = startExcelRow
  531. For Each dgvRow As DataGridViewRow In DGV3.Rows
  532. If rowIndex > endExcelRow Then Exit For
  533. Dim chemName As String = dgvRow.Cells("化工品名").Value.ToString()
  534. Dim weight As Double = Convert.ToDouble(dgvRow.Cells(3).Value)
  535. ' 確保 Excel 行存在
  536. Dim excelRow As IRow = sheet.GetRow(rowIndex)
  537. If excelRow Is Nothing Then
  538. excelRow = sheet.CreateRow(rowIndex)
  539. End If
  540. ' D欄(索引3) 寫化工品名
  541. Dim chemCell As ICell = excelRow.GetCell(2)
  542. If chemCell Is Nothing Then
  543. chemCell = excelRow.CreateCell(2)
  544. End If
  545. chemCell.SetCellValue(chemName)
  546. ' E欄(索引4) 寫重量
  547. Dim weightCell As ICell = excelRow.GetCell(3)
  548. If weightCell Is Nothing Then
  549. weightCell = excelRow.CreateCell(3)
  550. End If
  551. weightCell.SetCellValue(weight)
  552. rowIndex += 1
  553. Next
  554. ' ========== 設置字體樣式(可選) ==========
  555. Dim cellStyle As ICellStyle = workbook.CreateCellStyle()
  556. Dim font As IFont = workbook.CreateFont()
  557. font.FontHeightInPoints = 16
  558. font.Boldweight = FontBoldWeight.Normal
  559. cellStyle.SetFont(font)
  560. cellStyle.Alignment = HorizontalAlignment.Right
  561. cellStyle.VerticalAlignment = VerticalAlignment.Center
  562. ' 如果想給前面寫入的 D/E 欄都設置樣式,可在上面循環裡賦值
  563. ' 或者這裡再遍歷一次已寫入的行
  564. ' ========== 移除最後一行(若你不想保留 '总计' 那一行) ==========
  565. ' 假設 DGV3.Rows.Count = n,那麼最後一行索引就是 n (對 NPOI 來說)
  566. ' 如果確定要刪除那一行,就這樣做:
  567. Dim lastRowIndex As Integer = DGV3.Rows.Count
  568. If sheet.GetRow(lastRowIndex) IsNot Nothing Then
  569. sheet.RemoveRow(sheet.GetRow(lastRowIndex))
  570. End If
  571. ' ========== 重算總重量並取平均值 ==========
  572. totalWeight = DGV3.Rows.Cast(Of DataGridViewRow)().
  573. Sum(Function(r) Convert.ToDouble(r.Cells(4).Value))
  574. Dim avgWeight As Double = totalWeight / DGV3.Rows.Count
  575. ' ========== (C) B15: 領料單號, B16: 平均重量, E15: 調料日期 ==========
  576. ' Excel中 B15 => (Row=14, Col=1), B16 => (Row=15, Col=1), E15 => (Row=14, Col=4)
  577. ' 先確保 row14, row15 都存在
  578. Dim row14 As IRow = sheet.GetRow(16)
  579. If row14 Is Nothing Then row14 = sheet.CreateRow(16)
  580. Dim row15 As IRow = sheet.GetRow(17)
  581. If row15 Is Nothing Then row15 = sheet.CreateRow(17)
  582. ' B15 => 領料單號
  583. Dim cellB15 As ICell = row14.GetCell(1)
  584. If cellB15 Is Nothing Then cellB15 = row14.CreateCell(1)
  585. cellB15.SetCellValue(out_Number)
  586. ' B16 => 平均重量
  587. Dim cellB16 As ICell = row15.GetCell(1)
  588. If cellB16 Is Nothing Then cellB16 = row15.CreateCell(1)
  589. cellB16.SetCellValue(Math.Round(avgWeight, 0))
  590. ' E15 => 日期
  591. Dim cellE15 As ICell = row14.GetCell(4)
  592. If cellE15 Is Nothing Then cellE15 = row14.CreateCell(4)
  593. cellE15.SetCellValue(DateTimePicker1.Value.ToString("yyyy-MM-dd"))
  594. ' ------------------------ 5️⃣ 保存 Excel ------------------------
  595. Using fs As New FileStream(savePath, FileMode.Create, FileAccess.Write)
  596. workbook.Write(fs)
  597. End Using
  598. ' ------------------------ 6️⃣ 寫入數據庫 ------------------------
  599. Dim connectionString As String = connstring
  600. Using conn As New SqlConnection(connectionString)
  601. conn.Open()
  602. Using trans As SqlTransaction = conn.BeginTransaction()
  603. Try
  604. Dim insertQuery As String = "
  605. INSERT INTO HT_finish_out (out_no, [date], chem_name, qty, cust, color, rcp_name)
  606. VALUES (@out_no, @date, @chem_name, @qty, @cust, @color,@rcp_name)"
  607. For Each dgvRow As DataGridViewRow In DGV3.Rows
  608. Dim chemName As String = dgvRow.Cells("化工品名").Value.ToString().Trim()
  609. ' 假設某行叫 "总计" 就跳過
  610. If chemName = "总计" Then Continue For
  611. Dim cust As String = txtCustomer.Text.Trim()
  612. Dim color As String = txtColor.Text.Trim()
  613. Using cmd As New SqlCommand(insertQuery, conn, trans)
  614. cmd.Parameters.AddWithValue("@out_no", out_Number)
  615. cmd.Parameters.AddWithValue("@date", DateTimePicker1.Value)
  616. cmd.Parameters.AddWithValue("@chem_name", chemName)
  617. cmd.Parameters.AddWithValue("@qty", Convert.ToDouble(dgvRow.Cells(3).Value))
  618. cmd.Parameters.AddWithValue("@cust", cust)
  619. cmd.Parameters.AddWithValue("@color", color)
  620. cmd.Parameters.AddWithValue("@rcp_name", 處方清單_dgv.Rows(處方清單_dgv.CurrentCell.RowIndex).Cells("配料名称").Value)
  621. cmd.ExecuteNonQuery()
  622. End Using
  623. Next
  624. trans.Commit()
  625. Catch ex As Exception
  626. trans.Rollback()
  627. MessageBox.Show("數據庫錯誤:" & ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
  628. Return
  629. End Try
  630. End Using
  631. End Using
  632. ' ------------------------ 7️⃣ 自動打開 Excel ------------------------
  633. Process.Start("explorer.exe", savePath)
  634. ' ------------------------ 8️⃣ 提示成功 ------------------------
  635. MessageBox.Show("領料單已成功導出!單號:" & out_Number, "成功", MessageBoxButtons.OK, MessageBoxIcon.Information)
  636. End Sub
  637. Private Function GenerateSerialNumber(dateStr As String) As String
  638. Dim connectionString As String = connstring ' 請替換為你的資料庫連接字串
  639. Dim dateStr1 As String = DateTimePicker1.Value.ToString("yyMMdd") ' 取得 "250131" 格式
  640. ' **SQL 查詢,獲取當天的最大流水號**
  641. Dim query As String = "SELECT MAX(CAST(SUBSTRING(out_no, 9, LEN(out_no) - 8) AS INT)) " &
  642. "FROM HT_finish_out WHERE out_no LIKE 'P" & dateStr1 & "-%';"
  643. Dim maxSerial As Integer = 0
  644. Using conn As New SqlConnection(connectionString)
  645. conn.Open()
  646. Using cmd As New SqlCommand(query, conn)
  647. Dim result As Object = cmd.ExecuteScalar()
  648. If result IsNot DBNull.Value AndAlso result IsNot Nothing Then
  649. maxSerial = Convert.ToInt32(result)
  650. End If
  651. End Using
  652. End Using
  653. ' **流水號遞增**
  654. Dim newSerial As Integer = maxSerial + 1
  655. ' **返回格式化的領料單號**
  656. Return "P" & dateStr1 & "-" & newSerial.ToString()
  657. End Function
  658. Private Sub ExportToExcel(orderNumber As String)
  659. Dim savePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), orderNumber & ".xlsx")
  660. ' **(1) 創建 Excel Workbook**
  661. Dim workbook As IWorkbook = New XSSFWorkbook()
  662. Dim sheet As ISheet = workbook.CreateSheet("領料單")
  663. ' **(2) 設定標題行**
  664. Dim headerRow As IRow = sheet.CreateRow(0)
  665. For col As Integer = 0 To DGV3.Columns.Count - 1
  666. Dim cell As ICell = headerRow.CreateCell(col)
  667. cell.SetCellValue(DGV3.Columns(col).HeaderText)
  668. ' **設定標題格式**
  669. Dim headerStyle As ICellStyle = workbook.CreateCellStyle()
  670. Dim font As IFont = workbook.CreateFont()
  671. font.IsBold = True
  672. headerStyle.SetFont(font)
  673. headerStyle.Alignment = HorizontalAlignment.Center
  674. cell.CellStyle = headerStyle
  675. Next
  676. ' **(3) 填充數據**
  677. For row As Integer = 0 To DGV3.Rows.Count - 1
  678. Dim dataRow As IRow = sheet.CreateRow(row + 1)
  679. For col As Integer = 0 To DGV3.Columns.Count - 1
  680. Dim cell As ICell = dataRow.CreateCell(col)
  681. Dim value As Object = DGV3.Rows(row).Cells(col).Value
  682. If value IsNot Nothing Then
  683. If TypeOf value Is Decimal OrElse TypeOf value Is Double Then
  684. cell.SetCellValue(Convert.ToDouble(value))
  685. Else
  686. cell.SetCellValue(value.ToString())
  687. End If
  688. End If
  689. Next
  690. Next
  691. ' **(4) 自動調整欄位寬度**
  692. For col As Integer = 0 To DGV3.Columns.Count - 1
  693. sheet.AutoSizeColumn(col)
  694. Next
  695. ' **(5) 寫入文件**
  696. Using fs As New FileStream(savePath, FileMode.Create, FileAccess.Write)
  697. workbook.Write(fs)
  698. End Using
  699. ' **(6) 自動開啟 Excel 文件**
  700. If File.Exists(savePath) Then
  701. Process.Start("explorer.exe", savePath)
  702. End If
  703. End Sub
  704. Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnSaveAs.Click
  705. ' 使用 InputBox 获取用户输入的配料名称
  706. Dim rcpName As String = InputBox("请输入配料名称:", "输入配料名称", "")
  707. ' 检查用户是否输入了配料名称
  708. If String.IsNullOrEmpty(rcpName) Then
  709. MessageBox.Show("请输入配料名称", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
  710. Return
  711. End If
  712. ' 检查 rcp_name 是否存在,如果存在,则在后面加上 "副本"
  713. rcpName = CheckAndModifyRcpName(rcpName)
  714. ' 获取选择的日期
  715. Dim createdDate As DateTime = DateTimePicker1.Value
  716. ' 数据库连接字符串
  717. Dim connectionString As String = connstring
  718. ' 获取当前最大ID
  719. Dim maxId As Integer = GetMaxId(connectionString)
  720. Dim newId As Integer = maxId + 1 ' 生成新的ID
  721. ' 使用连接保存数据
  722. Using conn As New SqlConnection(connectionString)
  723. conn.Open()
  724. ' 遍历 dgv2 中的每一行,将数据插入到数据库
  725. For Each row As DataGridViewRow In 處方_dgv.Rows
  726. If row.IsNewRow Then Continue For ' 跳过新行
  727. ' 获取每一列的值
  728. Dim chemName As String = row.Cells("化工品名").Value.ToString()
  729. Dim percents As Double = Convert.ToDouble(row.Cells("份数").Value)
  730. ' 插入数据的 SQL 查询
  731. Dim query As String = "INSERT INTO HT_finish_rcp (rcp_name, chem_name, percents, created_date, id) " &
  732. "VALUES (@rcp_name, @chem_name, @percents, @created_date, @id)"
  733. Using cmd As New SqlCommand(query, conn)
  734. cmd.Parameters.AddWithValue("@rcp_name", rcpName)
  735. cmd.Parameters.AddWithValue("@chem_name", chemName)
  736. cmd.Parameters.AddWithValue("@percents", percents)
  737. cmd.Parameters.AddWithValue("@created_date", createdDate)
  738. cmd.Parameters.AddWithValue("@id", newId)
  739. ' 执行插入
  740. cmd.ExecuteNonQuery()
  741. newId += 1 ' 每次插入后,id+1
  742. End Using
  743. Next
  744. ' 显示保存成功的消息
  745. MessageBox.Show("数据已成功保存!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information)
  746. End Using
  747. End Sub
  748. Private Function CheckAndModifyRcpName(rcpName As String) As String
  749. Dim connectionString As String = connstring
  750. Dim query As String = "SELECT COUNT(*) FROM HT_finish_rcp WHERE rcp_name = @rcp_name"
  751. Using conn As New SqlConnection(connectionString)
  752. conn.Open()
  753. Using cmd As New SqlCommand(query, conn)
  754. cmd.Parameters.AddWithValue("@rcp_name", rcpName)
  755. Dim count As Integer = Convert.ToInt32(cmd.ExecuteScalar())
  756. ' 如果 rcp_name 已经存在,则添加 "副本"
  757. If count > 0 Then
  758. rcpName = rcpName & "副本"
  759. End If
  760. End Using
  761. End Using
  762. Return rcpName
  763. End Function
  764. Private Function GetMaxId(connectionString As String) As Integer
  765. Dim query As String = "SELECT MAX(id) FROM HT_finish_rcp"
  766. Using conn As New SqlConnection(connectionString)
  767. conn.Open()
  768. Using cmd As New SqlCommand(query, conn)
  769. Dim result As Object = cmd.ExecuteScalar()
  770. If result IsNot DBNull.Value AndAlso result IsNot Nothing Then
  771. Return Convert.ToInt32(result)
  772. Else
  773. Return 0 ' 如果没有记录,返回0
  774. End If
  775. End Using
  776. End Using
  777. End Function
  778. ' 删除指定配料名称的所有记录
  779. Private Sub DeleteRcpNameRecords(rcpName As String)
  780. Dim connectionString As String = connstring
  781. Dim query As String = "DELETE FROM HT_finish_rcp WHERE rcp_name = @rcp_name"
  782. Using conn As New SqlConnection(connectionString)
  783. conn.Open()
  784. Using cmd As New SqlCommand(query, conn)
  785. cmd.Parameters.AddWithValue("@rcp_name", rcpName)
  786. ' 执行删除操作
  787. cmd.ExecuteNonQuery()
  788. End Using
  789. End Using
  790. End Sub
  791. Private Sub RefreshDgv1()
  792. Dim connectionString As String = connstring
  793. Dim query As String = "SELECT rcp_name as 配料名称,created_date as 创建日期 FROM HT_finish_rcp group by rcp_name,created_date order by id"
  794. Using conn As New SqlConnection(connectionString)
  795. conn.Open()
  796. ' 使用 DataAdapter 将数据库数据填充到 DataTable
  797. Using da As New SqlDataAdapter(query, conn)
  798. Dim dt As New DataTable()
  799. da.Fill(dt)
  800. ' 将填充的数据绑定到 dgv1
  801. 處方清單_dgv.DataSource = dt
  802. End Using
  803. End Using
  804. End Sub
  805. End Class