this is my simple application , i try to updata ,but it is not working, in this example it shows only first reocrd and, try to update first record(i want to know the method of updating, so i can updates other records too)
data base has only two fields id,name
plz find the error
namespace DataAdap
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter dataAdapter;
private DataSet ds;
private DataTable dataTable;
private int currRec=0;
private int totalRec=0;
private int now;
private void btnView_Click(object sender, EventArgs e)
{
string connectionString="Data Source=Niro-PC\\SQLEXPRESS;Initial Catalog=UserData;Integrated Security=True";
conn = new SqlConnection(connectionString);
string selectqry = "SELECT * FROM UserInfo";
dataAdapter = new SqlDataAdapter(selectqry,conn);
ds = new DataSet();
dataAdapter.Fill(ds,"UserInfo");
dataTable = new DataTable();
dataTable = ds.Tables["UserInfo"];
totalRec = dataTable.Rows.Count;
FillControls();
InitializeCommands();
}
private void FillControls()
{
txtWorkerId.Text = dataTable.Rows[currRec]["id"].ToString();
txtName.Text = dataTable.Rows[currRec]["name"].ToString();
}
private void InitializeCommands()
{
dataAdapter.InsertCommand = conn.CreateCommand();
dataAdapter.InsertCommand.CommandText =
"INSERT INTO UserInfo" + "(id,name)" + "VALUES(@id,@name)";
AddParams(dataAdapter.InsertCommand, "id", "name");
dataAdapter.UpdateCommand = conn.CreateCommand();
dataAdapter.UpdateCommand.CommandText =
"UPDATE UserInfo SET" + "name = @name" + "WHERE id=@id";
AddParams(dataAdapter.UpdateCommand,"id","name");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void AddParams(SqlCommand cmd, params string[] cols)
{
foreach (string col in cols)
{
cmd.Parameters.Add("@"+col,SqlDbType.Char,0,col);
}
}
private void btnInsert_Click(object sender, EventArgs e)
{
DataRow row = dataTable.NewRow();
dataTable.Rows.Add(row);
totalRec = dataTable.Rows.Count;
currRec = totalRec - 1;
row["id"] = totalRec;
txtWorkerId.Text = totalRec.ToString();
txtName.Text = "";
}
private void btnSave_Click(object sender, EventArgs e)
{
DataRow row=dataTable.Rows[currRec];
row.BeginEdit();
row["name"] = txtName.Text;
row.EndEdit();
dataAdapter.Update(ds,"UserInfo");
ds.AcceptChanges();
}
}
}