我有一个场景,我可以保存名称和电话号码。但现在我想使用我的“保存”按钮作为点击网格视图数据的更新按钮。 同样在点击gridview数据后“保存”按钮会自动更改为“更新” 我想知道是否有任何事件或其他事情可以做到。使用一个按钮来保存和编辑Gridview在c#
我的表单图像
这里是我的代码 -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StoreProcedureExample
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-S80LS9D;Initial Catalog=ComboBoxTest;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter data;
DataSet ds;
int num = 0;
int i;
public Form1()
{
InitializeComponent();
cmd = new SqlCommand("UserInformation", conn);
data = new SqlDataAdapter(cmd);
ds = new DataSet();
data.Fill(ds);
this.userdataGridView1.DataSource = ds.Tables[0];
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveRecord();
ShowRecordAfterSaveAndEdit();
clearfilds();
}
public void SaveRecord()
{
cmd = new SqlCommand("insertupdate", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (userTextBox.Text == "")
{
num = 0;
}
else
{
num = int.Parse(userTextBox.Text);
}
cmd.Parameters.AddWithValue("@id", num);
cmd.Parameters.AddWithValue("@name", nameTextBox.Text);
cmd.Parameters.AddWithValue("@PhoneNumber", phoneNumberTextBox.Text);
if (saveButton.Text == "Save")
{
cmd.Parameters.AddWithValue("@Flag", 'S');
}
else
{
cmd = new SqlCommand("UpdateUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
}
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0 && saveButton.Text == "Save")
{
MessageBox.Show("record inserted");
}
else
{
MessageBox.Show("record Update");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
public void clearfilds()
{
userTextBox.Text = "";
nameTextBox.Text = "";
phoneNumberTextBox.Text = "";
saveButton.Text = "Save";
}
public void ShowRecordAfterSaveAndEdit()
{
cmd = new SqlCommand("UserInformation", conn);
data = new SqlDataAdapter(cmd);
ds = new DataSet();
data.Fill(ds);
this.userdataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void ShowData(object sender, EventArgs e)
{
int show = userdataGridView1.CurrentRow.Index;
userTextBox.Text = userdataGridView1.CurrentRow.Cells["Id"].Value.ToString();
nameTextBox.Text = userdataGridView1.CurrentRow.Cells["Name"].Value.ToString();
phoneNumberTextBox.Text = userdataGridView1.CurrentRow.Cells["PhoneNumber"].Value.ToString();
}
}
}
如果要更改按钮的标题,然后改变它......任何情况下需要 – pryashrma
我想知道如何改变这种标题 TIA – nazrul
saveButton.Text =“更新”; – pryashrma