hi
* i binded dropdown value from database in gridview
* then display the value in next column based on selecting dropdown value
* when i click add new row button . could not bind the dropdown value.
below are my code
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<contenttemplate> <asp:Label ID="Label1" runat="server" Text="2"></asp:Label>
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" onselectedindexchanged="DropDownList1_SelectedIndexChanged" runat="server" AutoPostBack="true" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button onclick="ButtonAdd_Click" ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
</contenttemplate></asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
Text="Button" />
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
} BindDropdownGrid();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
DropDownList box1 = (DropDownList )Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
DropDownList box1 = (DropDownList )Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid(); BindDropdownGrid();
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO tbl_sitework (code,work_type,amount,total_amt) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
splitItems[0] = Label1.Text;
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2],splitItems[3] );
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
//Display a popup which indicates that the record was successfully inserted
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private string GetConnectionString()
{
//"DBConnection" is the name of the Connection String
//that was set up from the web.config file
return System.Configuration.ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
}
protected void Button1_Click1(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add( Label1.Text +"," + box1.Text + "," + box2.Text + "," + box3.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
//private void BindDropdownGrid()
//{
// SqlConnection conn = new SqlConnection(GetConnectionString());
// conn.Open();
// SqlDataAdapter ad = new SqlDataAdapter("select * from tbl_workdetail", conn);
// DataSet ds = new DataSet();
// ad.Fill(ds, "work_type");
// foreach (GridViewRow row in Gridview1.Rows)
// {
// DropDownList ddlcity = (DropDownList)(Gridview1.Rows[row.RowIndex].Cells[1].FindControl("DropDownList1"));
// ddlcity.DataSource = ds;
// ddlcity.DataValueField = "work_type";
// ddlcity.DataTextField = "work_type";
// ddlcity.DataBind();
// }
//}
void BindDropdownGrid()
{
try
{
if (!IsPostBack)
{
foreach (GridViewRow row in Gridview1.Rows)
{
DropDownList ddlcity = (DropDownList)(Gridview1.Rows[row.RowIndex].Cells[1].FindControl("DropDownList1"));
ddlcity.Items.Add(new ListItem("--Select Contract--", ""));
ddlcity.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["connstring"].ConnectionString;
String strQuery = "select distinct(work_type) from tbl_workdetail";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlcity.DataSource = cmd.ExecuteReader();
ddlcity.DataValueField = "work_type";
ddlcity.DataTextField = "work_type";
ddlcity.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}
}
catch (Exception ex)
{
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in Gridview1.Rows)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ToString());
// txtSearch.Text = txtSearch.Text.Replace("'", "");
string query = "select * from tbl_workdetail where work_type=@work_type";
SqlCommand cmd = new SqlCommand(query, con);
DropDownList ddlcity = (DropDownList)(Gridview1.Rows[row.RowIndex].Cells[1].FindControl("DropDownList1"));
cmd.Parameters.AddWithValue("@work_type", ddlcity.Text);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox box2 = (TextBox)(Gridview1.Rows[row.RowIndex].Cells[2].FindControl("TextBox2"));
box2.Text = dr["work_amt"].ToString();
// txtfixsalary1.Text = dr["fixsalary1"].ToString();
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}