Update whole contents in gridview via single button click - c#

I need to update my whole gridview details via single button click. Now I have a coding. But I edit the grid view and click the update button, then the first row only update, remainins are not update. pls help. This is my code.
protected void Button8_Click(object sender, EventArgs e)
{
int RowIndex = 0;
{
GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
DataBind();
Response.Redirect(Request.Url.AbsoluteUri);
}
}

Because you are only specifying the index of first row. You need to loop through each row like this:-
int totalRows = GridView1.Rows.Count;
for (int RowIndex = 0; i < totalRows; RowIndex++)
{
GridViewRow row = GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
}
Response.Redirect(Request.Url.AbsoluteUri);
Also, I would suggest to create a separate layer to handle DB operations. Consider using the using statement while executing SQL related queries. Also read Can we stop using AddWithValue.
Update:
Side Note:
1) Bind your gridview inside !IsPostBack.
2) Don't bind the gridview again, either inside the loop or outside.
3) I don't find any reason to update the EditIndex using GridView1.EditIndex. Don't update it.

Related

Convert wpf datagrid to asp gridview

This c# code works fine in wpf framework.
Now I need this code in asp.net.
I am using GridView instead of DataGrid.
What changes do I have to do?
Here is my c# code:
DataRowView SelectedRowValue = (DataRowView)dataGrid1.SelectedValue;
byte[] ImageBytes = (byte[])SelectedRowValue.Row.ItemArray[1];
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO Images (Image) VALUES (#ImageSource)", con);
cmd2.Parameters.Add("#ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
cmd2.ExecuteNonQuery();
You can use Grid_RowUpdating Event using c#
protected void oGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("Label1");
TextBox txtImage = (TextBox)row.Cells[0].Controls[0];
//........
Then Update Command for MySQl which You are using//
MySqlCommand oMySqlCommand = connection.CreateCommand();
oMySqlCommand.CommandText = ""update detail set
Image='"+txtImage.Text+"'where id='"+userid+"'";
connection.Open();
command.ExecuteNonQuery();
//.......
etc//
GridView1.EditIndex = -1;
}

C# find row index (row number) in datagridview upon button click

This is the basic ui of my app and when i click the red (engaged room) button it should highlight the row in datagridview with cusid = 1, and no other row should be clickable.
I'm not able to find the row index (row number) in the dgv where cusid = 1, so that i can select/highlight it, specifically.
Could this be done, any helps?
I have a bookmyroom app and the i add my datagridview by using following code:
OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select id,cusid,cusname,timein,
timeout,duration,amount,remark from entry";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
and my checkbox column using this code;
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "logout";
checkColumn.HeaderText = "Logout";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10;
dataGridView1.Columns.Add(checkColumn);
Before you read the answer you should know in a windows application you can have multiple forms and you can do some tasks in other forms. For example, you can make your grid read only, then select a row and click on a check out button and perform editing actions in another form.
But based on your question:
You can assign an event handler for all buttons and then in the handler, for each row you can look in cusid column (column with index = 1) and check if the value equals to the button Text then activate logout cell, else make the row readonly:
private void button_Click(object sender, EventArgs e)
{
var button = sender as Button;
foreach (DataGridViewRow item in this.dataGridView1.Rows)
{
//This is the last row, ignore it.
if (item.IsNewRow)
continue;
//Compare value of cell1 with button text
//I supposed button.Tex is the value that you want to compare with cusid
if (item.Cells[1].Value.ToString() == button.Text)
{
//Make row editable
item.ReadOnly = false;
//Select the logout cell
this.dataGridView1.CurrentCell = item.Cells[5];
}
else
{
//Make row readonly
item.ReadOnly = true;
}
}
}
literally off the top of my head and untested, you may want to try something like this to get the next row down (if that's really what you need):
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn &&
e.RowIndex >= 0)
{
var nextRowNum = senderGrid.Rows[e.RowIndex] + 1;
// do what you need with the custId cell/value
// i.e. select that row and hilite it etc
}
}
apologies if I've misunderstood your requirement for the images you added.

Select the current row of GridView not working

I want to select the current row of GridView
int i = 0;
int a1, a2,a3;
string ida = Session["id"].ToString();
foreach (GridViewRow gv in grdreport.Rows)
{
Label id = (Label)grdreport.Rows[i].Cells[6].FindControl("lblid");
Label lblqus = (Label)grdreport.Rows[i].Cells[3].FindControl("Label1"); ;
Label lblans = (Label)grdreport.Rows[i].Cells[4].FindControl("Label2");
try //geting Officer ID
{
int j = 0;
DataTable dtofc = new DataTable();
conn.Open();
SqlCommand cmd = new SqlCommand("SP_FAQ_CCA", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("qryflg", "Officer1");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtofc);
officerDept = dtofc.Rows[j]["DeptId"].ToString();
QAId = dtofc.Rows[j]["QAId"].ToString();
conn.Close();
}
It only selects the first row of GridView even though I click on 2nd row.
I also tried this :
Label id = (Label)grdreport.currentrow.cell[6].FindControl("lblid");
Label id = (Label)gv.FindControl("lblid");
but it's not working as well, Please help me with this.
It should be:
Label id = (Label)gv.Cells[6].FindControl("lblid");
Label lblqus = (Label)gv.Cells[3].FindControl("Label1");
Label lblans = (Label)gv.Cells[4].FindControl("Label2");
If you want it inside a button click event handler:
protected void btn_Click(object sender, EventArgs e)
{
//clicked button
LinkButton btn= (LinkButton)sender;
// row of the clicked button
GridViewRow containerRow = (GridViewRow)(btn).NamingContainer;
Label id = (Label)containerRow .Cells[6].FindControl("lblid");
Label lblqus = (Label)containerRow .Cells[3].FindControl("Label1");
Label lblans = (Label)containerRow .Cells[4].FindControl("Label2");
/// remaining code
}

selected value of dropdown list not changing in template field

I have a dropdown list in a template field that has it's selected value on load set to another field in the gridview. In the rowupdating event the dropdown goes back to the initial selected value and does not retain the new value. I have the method that fills the grid wrapped in a if this.page.IsPostBack on the page_load event. How do I bind the control's new selected value during rowupdating event and ignore it's initial databind??
I have the auto post back property set to true as well.
Here is the rowupdating event ( I am actually inserting into a different table NOT updating this grid)
protected void grd_add_bins__RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grd_add_bins.Rows[e.RowIndex];
//int id = Int32.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
Label room1 = (Label)row.FindControl("grd_add_room");
Label grower1 = (Label)row.FindControl("grd_add_grower_id");
TextBox bins1 = (TextBox)row.FindControl("grd_add_txtbins_to_pack");
DropDownList packas1 = (DropDownList)row.FindControl("grd_add_ddl_pack_as");
TextBox block1 = (TextBox)row.FindControl("grd_add_txt_block");
Label pool1 = (Label)row.FindControl("grd_add_pool");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into t_run_schedule_lots " +
"(record_key,room_id,grower_id,block_id,pool_id,total_bins,pack_as) " +
"values (#rec_id,#room,#grower,#block,#pool,#bins,#pack_as)";
cmd.Parameters.Add("#rec_id", SqlDbType.VarChar).Value = lblRec_key.Text;
cmd.Parameters.Add("#room", SqlDbType.VarChar).Value = room1.Text;
cmd.Parameters.Add("#grower", SqlDbType.VarChar).Value = grower1.Text;
cmd.Parameters.Add("#bins", SqlDbType.Int).Value = Convert.ToInt32(bins1.Text);
cmd.Parameters.Add("#pack_as", SqlDbType.VarChar).Value = packas1.Text;
cmd.Parameters.Add("#block", SqlDbType.VarChar).Value = block1.Text;
cmd.Parameters.Add("#pool", SqlDbType.VarChar).Value = pool1.Text;
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
// execute insert statement
cmd.ExecuteNonQuery();
this.sqlConnection1.Close();
fill_grid();<-- fills other grid that shows the result of the insert
fill_bins_grid();<-- fills this grid
//Reset the edit index.
grd_add_bins.EditIndex = -1;
//Bind data to the GridView control.
grd_add_bins.DataBind();
}
You need a OnSelectedIndexChanged method.

Gridview Bulk Update

From this link:
asp.net grid view bulk updating all cells
I did the following:
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
// foreach (GridViewRow row in GridView1.Rows)
// {
int RowIndex = 0;
GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];
Int32 intresortID = Convert.ToInt32(Request.QueryString["TypeID"]);
Label dtm = row.FindControl("Label1") as Label;
Label strRoomType = row.FindControl("strRoomTypeLabel") as Label;
Label strDescription = row.FindControl("Label3") as Label;
TextBox Qty = row.FindControl("intQtyTextBox") as TextBox;
TextBox Price = row.FindControl("curPriceTextBox") as TextBox;
Label intWSCode = row.FindControl("intWSCodeLabel") as Label;
string connStr = ConfigurationManager.ConnectionStrings["bedbankstandssConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("Update tblAvailable set intqty=#intQty, curprice=#curprice where intresortid=#intresortid and dtm=#dtm and strroomtype=#strroomtype",Con);
//SqlParameter ddtm= new SqlParameter("#dtm",dtm) ;
//SqlParameter sstrRoomType = new SqlParameter("#strroomtype", strRoomType);
//SqlParameter qQty = new SqlParameter("#intQty", Qty);
//SqlParameter pPrice =new SqlParameter("#curPrice",Price);
//SqlParameter resortID = new SqlParameter("#intResortID", intresortID);
cmd.Parameters.AddWithValue("#dtm",dtm.Text.Trim());
cmd.Parameters.AddWithValue("#strroomtype",strRoomType.Text.Trim());
cmd.Parameters.AddWithValue("#intQty", Qty.Text.Trim());
cmd.Parameters.AddWithValue("#curPrice",Price.Text.Trim());
cmd.Parameters.AddWithValue("#intResortID",intresortID);
Con.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
DataBind();
// }
}
But only one row gets updated, the first one.
Would somebody be able to tell me where I went wrong please.
You have commented out the loop, so why are you wondering that only one row is updated?
foreach (GridViewRow row in GridView1.Rows)
{
// ...
}
Apart from that, use the using-statement for your SqlConnection and SqlCommand to ensure that is gets disposed/closed.
using(SqlConnection Con = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand("Update tblAvailable set intqty=#intQty, curprice=#curprice where intresortid=#intresortid and dtm=#dtm and strroomtype=#strroomtype",Con))
{
// ...
}
}

Categories