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
}
Related
I have an aspx page used for evaluation. One of the requirements for the page is to create multiple Gridviews to act as the evaluation form. The Gridview is populated by the questions from my database and textbox alongside the questions. So Column1 = Questions and Column2 = Textbox. The number of Gridviews created depends on the value that the user typed inside a textbox.
My problem is, since it is dynamically created, I don't know how am I suppose to retrieve the values typed in the textbox. I need them to be saved on my database.
How should I do this? Or is there a better approach to this?
My Code:
protected void btnOk_Click(object sender, EventArgs e)
{
btnSave.Visible = true;
int parCounter = Convert.ToInt32(participants.Text);
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string sql = "select * from evalForm";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
for (i = 1; i <= parCounter; i++)
{
GridView objGV = new GridView();
objGV.AutoGenerateColumns = false;
objGV.ID = "GV"+i;
for (int col = 0; col < dt.Columns.Count; col++)
{
BoundField boundfield = new BoundField();
boundfield.DataField = dt.Columns[col].ColumnName.ToString();
boundfield.HeaderText = dt.Columns[col].ColumnName.ToString();
objGV.Columns.Add(boundfield);
}
TemplateField tempfield = new TemplateField();
tempfield.HeaderText = "Score";
objGV.Columns.Add(tempfield);
objGV.RowDataBound += new GridViewRowEventHandler(myGrid_RowDataBound);
compName.Visible = true;
fromDate.Visible = true;
toDate.Visible = true;
participants.Visible = true;
objGV.DataSource = dt;
objGV.DataBind();
Panel1.ContentTemplateContainer.Controls.Add(objGV);
}
}
protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtScore = new TextBox();
txtScore.ID = "tbScore";
e.Row.Cells[2].Controls.Add(txtScore);
}
}
To find any Dynamic controls you have to use FindControl. This also works for GridView controls.
//loop the dynamic gridviews
for (i = 1; i <= parCounter; i++)
{
//use findcontrol and cast back to a gridview
GridView gv = Panel1.ContentTemplateContainer.FindControl("GV" + i);
//loop all the rows in the gridview
foreach (GridViewRow row in gv.Rows)
{
//use findcontrol again to find the textbox
TextBox tb = row.FindControl("tbScore") as TextBox;
}
}
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.
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.
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();
}
}
}
}
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))
{
// ...
}
}