Gridview Bulk Update - c#

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))
{
// ...
}
}

Related

update button on nested gridview asp.net c#

I have this nested grid view in which the data are shown in textboxes and i also have an update button but when i click the button instead of updating the data on the data table it just updates the new value on the grid view itself and shows it along with the old value and i don't get any error though. Please help me thanks.
the code:
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
using (OleDbConnection con = new OleDbConnection(strConnString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandText = query;
using (OleDbDataAdapter sda = new OleDbDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = gvSDate.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvSDate2 = e.Row.FindControl("gvSDate2") as GridView;
gvSDate2.DataSource = GetData(string.Format("select ID, Function, FunctionDate, FunctionTime, CelebrateName from function where ID={0}", ID));
gvSDate2.DataBind();
}
}
protected void gvSDate2_RowDataBound(object sender, GridViewRowEventArgs f)
{
if (f.Row.RowType == DataControlRowType.DataRow)
{
GridView gvSDate2 = f.Row.FindControl("gvSDate2") as GridView;
TextBox textFunction = f.Row.FindControl("textFunction") as TextBox;
TextBox textFunctionDate = f.Row.FindControl("textFunctionDate") as TextBox;
TextBox textFunctionTime = f.Row.FindControl("textFunctionTime") as TextBox;
TextBox textCelebrateName = f.Row.FindControl("textCelebrateName") as TextBox;
Label lblID = f.Row.FindControl("lblID") as Label;
Button update1 = f.Row.FindControl("update1") as Button;
string Function = textFunction.Text;
string FunctionDate = textFunctionDate.Text;
string FunctionTime = textFunctionTime.Text;
string CelebrateName = textCelebrateName.Text;
string ID1 = lblID.Text;
update1.Click += (send, g) =>
{
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string updateQuery = "UPDATE function SET Function=#Function, FunctionDate=#FunctionDate, FunctionTime=#FunctionTime, CelebrateName=#CelebrateName WHERE ID=#ID";
command.CommandType = CommandType.Text;
command.CommandText = updateQuery;
command.Parameters.AddWithValue("#ID", ID1);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#CelebrateName", CelebrateName);
};
}
}

Update whole contents in gridview via single button click

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.

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
}

How to Bind DropDown in GridView

I have drop-down that is in a gridview and it is binding but the problem is that is binding only the first row and keep binding the same value the rest of the gridview. I am expecting a drop down for each each row in the gridview and the content of the drop down will be different based on ID in the gridvew. In one row it might be Yes, No and the other one might be Yes, No, NA. Here is my code:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
foreach (GridViewRow grdRow in GridView1.Rows)
{
//get current index selected
int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = (DropDownList)(GridView1.Rows[grdRow.RowIndex].Cells[2].FindControl("ddl_Answer"));
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ");
cmd1.Connection = con2;
con2.Open();
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
con2.Close();
}
}
You are already in the RowDataBound event for the GridView. This is fired once per row so you don't need to then further foreach (GridViewRow grdRow in GridView1.Rows) each time through. You should be able to simplify your code down to:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
//get current index selected
int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
{
con2.Open();
using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ", con2))
{
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
}
}
}
}

Combobox in DataGridView

How to display text on combo box in a DataGridView at run time from database?
For example, if am updating my text in database from combo box in DataGridView next time I want to display that text in combobox column.
sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
selectQueryString = "SELECT Code,CompanyName,FinancialYearStart,FinancialYearEnd,UserName,RoleP FROM CompanyInformation";
sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView3.DataSource = bindingSource;
dataGridView3.Controls.Clear();
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
private void button10_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
con.Open();
// if (dataGridView3.Columns.Count >= 4 && dataGridView3.Columns.Count < 10)
// {
int i = dataGridView3.Rows.Count;
int r = 0;
for (int s = 0; s < i; s++)
{
try
{
string Role = dataGridView3.Rows[s].Cells[0].Value.ToString();
int Cod = Convert.ToInt32(dataGridView3.Rows[s].Cells[1].Value.ToString());
if (Role != "")
{
SqlCommand cmd = new SqlCommand("update CompanyInformation SET RoleP=#Role where Code=#Cod", con);
cmd.Parameters.AddWithValue("#Cod", Cod);
cmd.Parameters.AddWithValue("#Role", Role);
r = cmd.ExecuteNonQuery();
}
}
catch
{
}
}
if (r >= 1)
{
MessageBox.Show("Update Successful");
SuperUser obj = new SuperUser();
this.Hide();
this.ParentForm.Hide();
}
You can go with this:
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
After that check
foreach (DataGridViewRow row in dataGridView3.Rows)
{
(row.Cells[1] as DataGridViewComboBoxCell).Value = yourvalue;
}

Categories