How to Bind DropDown in GridView - c#

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();
}
}
}
}

Related

I have a problem with link datagridview and custome database column

private void Purchases_Load(object sender, EventArgs e)
{
com.Connection = con;
con.Open();
com.CommandText = "select * from Items";
com.ExecuteNonQuery();
DataTable dt7 = new DataTable();
SqlDataAdapter da7 = new SqlDataAdapter(com);
da7.Fill(dt7);
ComboColumn.DataSource = dt7;
ComboColumn.DisplayMember = "Name";
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
com.Connection = con;
com.CommandText = "select ID from Items where Name = '" + ComboColumn + "' ";
con.Open();
com.ExecuteNonQuery();
SqlDataReader dr;
dr = com.ExecuteReader();
while (dr.Read())
{
string id = (string)dr["ID"].ToString();
}
con.Close();
}
I have sql db table contains ID and Items.
also, I have winform and I'm using DataGrid type "DataGridViewComboBoxColumn" to select the items from db table and it's working perfectly
now, The problem is I need to show the following "ID column" to the second column in DGV while I selecting the items from "DataGridViewComboBoxColumn".
So, I need help to link a specific column in database which is (ID) with a specific column on datagrid column type "DataGridViewTextBoxColumn" when user select items from the gdv ComboBoxColumn.
note: 1st scop of code working and giving me items from db.
2nd scop of code not working and I can't handle it for retrieve ID from db table!!
The answer is here!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewComboBoxCell comboBoxCell = (row.Cells[2] as DataGridViewComboBoxCell);
comboBoxCell.Items.Add("Select Goods");
comboBoxCell.Value = "Select Goods";
DataTable dt_1 = this.GetData("SELECT ID,Name from Goods");
foreach (DataRow drow in dt_1.Rows)
{
string customerId = drow[0].ToString();
comboBoxCell.Items.Add(drow[0] + "-" + drow[1]);
if (customerId != "3")
{
if (row.Cells[2].Value.ToString() == customerId)
{
comboBoxCell.Value = drow[1];
}
}
}

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

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);
};
}
}

Set selected value of DropDownList based on database

I have a dropdownlist in a gridview and when the textbox is changed, I would like the selected value in the dropdownlists (three separate ones in total) to match the data in the database. The code in the textbox changed event is below:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
string connectionString = ConfigurationManager.ConnectionStrings["*******"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT one, two, three FROM table WHERE id = " + TextBox1.Text;
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
int num = sda.Fill(ds);
if (num > 0)
{
GridView1.Visible = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
if (num == 0)
{
GridView1.Visible = false;
}
else
{
BindGrid();
}
}
}
Try using the RowDataBound event. For this to work, the drop-down-lists must already be populated with values, and in the event, the SelectedValue will be assigned.
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// this assumes the drop-down-list columns are the first, second, and third columns (ordinal positions 0, 1, and 2)
DropDownList ddl1, ddl2, ddl3;
ddl1 = (DropDownList)e.Row.Cells[0].Controls[0];
ddl2 = (DropDownList)e.Row.Cells[1].Controls[0];
ddl3 = (DropDownList)e.Row.Cells[2].Controls[0];
DataRow currentRow = (DataRow)e.Row.DataItem;
ddl1.SelectedValue = currentRow[0].ToString();
ddl2.SelectedValue = currentRow[1].ToString();
ddl3.SelectedValue = currentRow[2].ToString();
}
}

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