How to fire textboxchanged event on dynamically added textbox in gridview - c#

In my project, I can add n number of textbox in gridview dynamically. My problem is, I want to fire textboxchanged event, if user change the text of any textbox in any row of gridview.
HTML CODE:
<asp:GridView ID="GridView1" runat="server"
Width="907px" style="text-align: center" CellPadding="4" ForeColor="#333333"
GridLines="None" onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
ADDING COLUMNS IN GRIDVIEW:
foreach (string a in crcl)
{
SqlCommand cmd1 = new SqlCommand("select qty from purchaseinstruction where project ='" + DropDownList1.SelectedItem.ToString() + "' AND circle = '" + a + "' AND item = 'BIFURCATION' AND material = '" + mat + "'", agr);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
string val = dr1[0].ToString();
if (val.Length > 0)
{
row[a] = val;
}
else
{
row[a] = 0;
}
}
else
{
row[a] = 0;
}
dr1.Dispose();
}
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
ADDING TEXTBOX ON ROWBOUND:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i = 3;
if (e.Row.RowType == DataControlRowType.DataRow)
{
crcl = (List<string>)ViewState["bdi2"];
foreach(string a in crcl)
{
TextBox TextBox101 = new TextBox();
TextBox101.ID=a;
TextBox101.Width = 60;
TextBox101.Text = (e.Row.DataItem as DataRowView).Row[a].ToString();
TextBox101.AutoPostBack = true;
e.Row.Cells[i].Controls.Add(TextBox101);
i++;
}
}
}
Here I have three problems
1. After postback textboxs get dispose
2. How to retain the value of textboxes for textboxchange?
3. How to know which textbox fire textboxchange

Related

How to add View to Multiview dynamically in asp.net

I have placed MultiView in UpdatePanel and added Views dynamically, each has GridView control. I'm able to display only the View which is set at first time. I have added static button for "Next" & "Back". An error "ActiveViewIndex is being set to '0'. It must be smaller than the current number of View controls '0'. For dynamically added views, make sure they are added before or in Page_PreInit event.Parameter name: value" occurs, when I click any button including these two.
Code-behind:
protected void MultiView1_Load(object sender, EventArgs e)
{
try
{
if (DropDownList4.SelectedIndex > 0)
{
int i = 1;
SqlCommand cmd = new SqlCommand("select DISTINCT(schedule) from tender where project = '" + DropDownList1.SelectedItem.ToString() + "'", agr);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string schedule = dr[0].ToString().Trim();
GridView Gridview1 = new GridView();
Gridview1.ID = "Gridview" + i.ToString();
Gridview1.RowDataBound +=new GridViewRowEventHandler(Gridview1_RowDataBound);
Gridview1.EnableViewState = true;
Gridview1.HeaderStyle.BackColor = System.Drawing.Color.Silver;
Gridview1.HeaderStyle.ForeColor = System.Drawing.Color.White;
Gridview1.HeaderStyle.Font.Bold = true;
Gridview1.ForeColor = System.Drawing.Color.Gray;
Gridview1.AlternatingRowStyle.BackColor = System.Drawing.Color.White;
Gridview1.GridLines = GridLines.None;
Gridview1.RowStyle.BackColor = System.Drawing.ColorTranslator.FromHtml("#EFF3FB");
Gridview1.HorizontalAlign = HorizontalAlign.Center;
Gridview1.Width = 900;
DataTable dt = new DataTable();
dt.Columns.Add("SN", typeof(string));
dt.Columns.Add("SCHEDULE", typeof(string));
dt.Columns.Add("MATERIAL", typeof(string));
dt.Columns.Add("UNIT", typeof(string));
dt.Columns.Add("PREVIOUS BOQ QTY", typeof(string));
dt.Columns.Add("CURRENT QTY", typeof(string));
int j = 1;
SqlCommand cmd1 = new SqlCommand("select material from tender where project = '" + DropDownList1.SelectedItem.ToString() + "' AND schedule = '" + schedule + "' order by schedulesubsn ", agr);
SqlDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
DataRow row = dt.NewRow();
string mat = dr1[0].ToString().Trim();
row["SN"] = j;
row["SCHEDULE"] = schedule;
row["MATERIAL"] = mat;
row["UNIT"] = Calfunc.getunit(mat);
row["PREVIOUS BOQ QTY"] = Calfunc.GetLocationBOQ(DropDownList1.SelectedItem.ToString(), DropDownList2.SelectedItem.ToString(), DropDownList3.SelectedItem.ToString(), DropDownList4.SelectedItem.ToString(), schedule, mat);
dt.Rows.Add(row);
j++;
}
dr1.Dispose();
View view = new View();
view.ID = schedule;
view.Controls.Add(Gridview1);
MultiView1.Views.Add(view);
Gridview1.DataSource = dt;
Gridview1.DataBind();
i++;
}
dr.Dispose();
MultiView1.ActiveViewIndex = i-3;
}
}
catch (Exception ex)
{
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (MultiView1.ActiveViewIndex > 0)
{
MultiView1.ActiveViewIndex = MultiView1.ActiveViewIndex - 1;
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (MultiView1.Views.Count-1 > MultiView1.ActiveViewIndex)
{
TextBox2.Text = (MultiView1.ActiveViewIndex + 1).ToString();
}
}
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox TextBox101 = new TextBox();
TextBox101.ID = "TextBox_C_QTY";
TextBox101.Width = 70;
TextBox101.Text = (e.Row.DataItem as DataRowView).Row["CURRENT QTY"].ToString();
e.Row.Cells[5].Controls.Add(TextBox101);
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<div style="overflow-x:auto;">
<asp:MultiView ID="MultiView1" runat="server" onload="MultiView1_Load">
</asp:MultiView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
I've searched for the solution but didn't find any satisfactory or workable (for me).

How to copy data from textbox to another textbox, added dynamically in gridview, without postback

I've dynamically added n number of textbox in gridview and bind the data on them. I want a code behind function/method to sum textbox1, textbox2.....textboxn in textboxtotal, if user change the value in any text box. I can't add postback with these textboxes, because after postback textbox get disposed.
Code for adding Columns to Gridview dynamically
foreach (string a in crcl)
{
SqlCommand cmd1 = new SqlCommand("select qty from purchaseinstruction where project ='" + DropDownList1.SelectedItem.ToString() + "' AND circle = '" + a + "' AND item = 'BIFURCATION' AND material = '" + mat + "'", agr);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
string val = dr1[0].ToString();
if (val.Length > 0)
{
row[a] = val;
value = value + decimal.Parse(val);
}
else
{
row[a] = 0;
}
}
else
{
row[a] = 0;
}
dr1.Dispose();
row["TOTAL"] = value;
}
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
Adding Textbox control on rowbound:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i = 3;
if (e.Row.RowType == DataControlRowType.DataRow)
{
crcl = (List<string>)ViewState["bdi2"];
foreach(string a in crcl)
{
TextBox TextBox101 = new TextBox();
TextBox101.ID=a;
TextBox101.Width = 60;
TextBox101.Text = (e.Row.DataItem as DataRowView).Row[a].ToString();
e.Row.Cells[i].Controls.Add(TextBox101);
i++;
}
TextBox TextBox102 = new TextBox();
TextBox102.ID = "TOTAL";
TextBox102.Width = 60;
TextBox102.Text = (e.Row.DataItem as DataRowView).Row["TOTAL"].ToString();
e.Row.Cells[i].Controls.Add(TextBox102);
}
}
Here is a little example to get you started. Add a unique class name to the TextBoxes in the GridView. Then the jQuery can bind the onblur event to them.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" CssClass="GridTextBox"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" CssClass="GridTextBox"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" CssClass="GridTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here the javascript function that is called when the TextBox loses focus.
First the ID of the TextBox that triggers the event is split into pieces to get the ID's of the other two TextBoxes in the row (
in my case the ID looks like this ContentPlaceHolder1_GridView1_TextBox1_0).
Then it's just a matter of adding the values.
<script type="text/javascript">
$(document).ready(function () {
$('.GridTextBox').blur(function () {
var idString = this.id.split("_");
var tb1 = idString[0] + "_" + idString[1] + "_TextBox1_" + idString[3];
var tb2 = idString[0] + "_" + idString[1] + "_TextBox2_" + idString[3];
var tb3 = idString[0] + "_" + idString[1] + "_TextBox3_" + idString[3];
var total = parseInt($("#" + tb1).val()) + parseInt($("#" + tb2).val());
if (!isNaN(total)) {
$("#" + tb3).val(total);
}
});
});
</script>
You can create Javascript function in code behind, like this (if you are using WebForms):
string myScript = "function sumTextBoxes() { var arr = document.getElementsByClassName('txtBox');\n";
myScript += "var total=0;\n";
myScript += "for(var i=0;i<arr.length;i++){\n";
myScript += "if(parseInt(arr[i].value))\n";
myScript += "total += parseInt(arr[i].value);}\n";
myScript += "document.getElementById('total').value = total;}\n";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, true);
Now, add css class to your dynamicaly created TextBoxes (add this):
TextBox101.CssClass = "txtBox";
Also, TextBox which displays the sum should be named like this:
TextBox102.ID = "total";

How to retrieve the input values from Dynamically generated TextBoxes

I have a DropDownList bounded with list of items from SqlDataSource. With the help of DropDownList_SelectedIndexchanged() function i am able to generate two dynamic text boxes.
Required Output: I need to search for the data based on the textbox inputs given by the user and Searched data shall be displayed in JQGrid with the help of Button_Click() event.
Current Issue: The textbox inputs are not retrieved and it always retrieved as null string "".
Exception obtained is : Incorrect Syntax near "AND" (SQL Query)
How to solve this issue?
My aspx code:
<asp:Panel ID="Panel5" runat="server" Height="221px">
<span style="font-size: 135%; font-family: Verdana; font-weight: bold"> Search Functionalities </span>
<asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="column_list_for_filter" DataTextField="All_Columns" DataValueField="All_Columns" OnSelectedIndexChanged ="DropDownList5_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="column_list_for_filter" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" SelectCommand="SELECT COLUMN_NAME 'All_Columns' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='RESULT' "></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Small" OnClick="Button1_Click" Text="Search Flow Periods" Width="144px" />
<asp:Table ID="dynamic_filter_table" runat="server" ToolTip="Results">
</asp:Table>
</asp:Panel>
My C# code:
//Creation of Two Dynamic Text Box Web Controls on DDL selection
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
createdynamiccontrols();
}
/*Two Text Boxes and Two Labels for input and search the FlowPeriod and display in JqGrid
thru button click event*/
protected void createdynamiccontrols()//(string ID1, string ID2)
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row;
row = new TableRow();
TableCell cell1 ;
cell1 = new TableCell();
TableCell cell2;
cell2= new TableCell();
// Set a unique ID for each TextBox added
TextBox tb1;
tb1 = new TextBox();
TextBox tb2;
tb2 = new TextBox();
Label lbl1;
lbl1 = new Label();
Label lbl2;
lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + i.ToString();
tb2.ID = "upperbound_"+ i.ToString() ;
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
// Add the control to the TableCell
cell1.Controls.Add(lbl1);
cell1.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
// Add the TableCell to the TableRow
row.Cells.Add(cell1);
row.Cells.Add(cell2);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
Button1.EnableViewState = true;
ViewState["Button_1"] = true;
}
protected override object SaveViewState()
{
object[] viewstate = new object[2];
List<string> dynamic_text_values = new List<string>();
foreach (TableRow row in dynamic_filter_table.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[1] is TextBox)
{
dynamic_text_values.Add(((TextBox)cell.Controls[1]).Text);
}
}
}
viewstate[0] = dynamic_text_values.ToArray();
viewstate[1] = base.SaveViewState();
return viewstate;
}
protected override void LoadViewState(object savedState)
{
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (txtValues.Length > 0)
{
createdynamiccontrols();
}
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
createdynamiccontrols();
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
string testt = lowerboundd.Text;
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT ColumnName1,Columnname2 FROM RESULT WHERE " + DropDownList5.SelectedValue + " >= " + lowerboundd.Text + " AND " + DropDownList5.SelectedValue + " <= " + upperbound.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
/*Error occurs here as Incorrect Syntax near AND as the string obtained is "" and not
textbox inputs*/
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
protected void Page_Load(object sender, EventArgs e)
{
//Dynamic controls creation on Page Load
if (!IsPostBack)
{
BindDropDownLists();
}
dynamic_filter_table.EnableViewState = true;
}
You need to move BindDropDownLists(); to the Page_Init method from Page_Load or else the page lifecycle will not find the viewstate and attach to your controls. By the time you are in Page_Load you are too late. Make sure your logic to create the controls in init and your logic to retrieve the data in load/events and you should see some results.
You don't need the viewstate stuff as that will automagically wire itself up, you can't create the dynamic controls in a control event like click or selectedindexchanged as thats too late in the lifecycle. The dynamic controls need to be created before load for the viewstate to be wired by the time load comes around.
More Reading

Radio button list selected value not persistent in asp.net

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

issue with populating dropdownlist in gridview edit mode in c#

I am having editable Gridview with column named Country which has so long listing.
When I am showing data the value of Country is in Label but when I choose edit should show DropDownList with country listings. I am able to show listings. it should show the country selected as that was in label.
I have tried with this but dropdownlist is filled with System.Row.DataRowView also it is not set at SelectedValue given as cvalue
aspx page
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#Bind("Country")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px"
Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>
<EditItemTemplate>
.cs file
void gvhoteldetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
string cnm="",cvalue="";
string getCountry = "Select * from tbl_countrynames where `Name`='" + cname + "'";
string getCountrynames = "Select * from tbl_countrynames";
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd1 = new MySqlCommand(getCountrynames, con);
DataSet ds1 = new DataSet();
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd1);
da1.Fill(ds1);
MySqlCommand cmd = new MySqlCommand(getCountry, con);
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
cnm = ds.Tables[0].Rows[0]["Name"].ToString();
cvalue = ds.Tables[0].Rows[0]["Value"].ToString();
}
DropDownList ddlcountry = (DropDownList)e.Row.FindControl("ddlCCountry");
ddlcountry.DataSource = ds1;
ddlcountry.SelectedValue = cvalue;
ddlcountry.DataBind();
}
What could be wrong?
This worked for me. When populating the GridView, you should populate each DropDownList in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
numberFormatDA formatDA = new numberFormatDA();
DataTable mytable = new DataTable();
DataColumn formatIDcolumn = new DataColumn("fkNumberFormat");
DataColumn formatNameColumn = new DataColumn("numberFormat");
mytable.Columns.Add(formatIDcolumn);
mytable.Columns.Add(formatNameColumn);
DataSet ds = new DataSet();
ds = formatDA.getNumberFormatsDS();
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox txtSite = (TextBox)e.Row.FindControl("txtIDSite");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlNumberFormat");
DataRow[] rows = ds.Tables[0].Select();
foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["fkNumberFormat"] = row["idnumberFormat"];
newrow["numberFormat"] = row["numberFormat"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "numberFormat";
ddl.DataValueField = "fkNumberFormat";
int numberFormatID = 0;
Label lblFormatID = (Label)e.Row.FindControl("numberFormatLabel");
numberFormatID = Int32.Parse(lblFormatID.Text);
ddl.SelectedValue = numberFormatID.ToString();
ddl.DataBind();
}
}
Hope this helps!
This way you can make it work but I know there's a much better way to achieve this..
Try this for now...
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow gvr = GridView1.Rows[e.NewEditIndex];
Label lb = (Label)gvr.FindControl("lblCountry");
GridView1.EditIndex = e.NewEditIndex;
binddata();
getselected(lb.Text);
}
private void getselected(string text)
{
GridViewRow gvr = GridView1.Rows[GridView1.EditIndex];
DropDownList dr = (DropDownList)gvr.FindControl("ddlCCountry");
dr.SelectedIndex = dr.Items.IndexOf(dr.Items.FindByText(text));
}
protected void gvGeneralMaster_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.NewEditIndex];
ViewState["COUNTRY"] = ((Label)gvRow.FindControl("lblCountry")).Text.Trim();
ViewState["STATE"] = ((Label)gvRow.FindControl("lblState")).Text.Trim();
gvGeneralMaster.EditIndex = e.NewEditIndex;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
protected void gvGeneralMaster_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.RowIndex];
oPRP._GeneralCode = int.Parse(((Label)gvRow.FindControl("lblEGenCode")).Text.Trim());
oPRP._GenaralName = ((TextBox)gvRow.FindControl("txtECity")).Text.Trim();
oPRP._StateName = ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() : "";
oPRP._CountryName = ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() : "";
oPRP._Remarks = ((TextBox)gvRow.FindControl("txtERemarks")).Text.Trim();
oPRP._Active = ((CheckBox)gvRow.FindControl("chkEditActive")).Checked;
oPRP._ModifiedBy = Session["CurrentUser"].ToString();
oDAL.SaveUpdateGeneralMaster("UPDATE", oPRP);
gvGeneralMaster.EditIndex = -1;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
It's too late for the answer, but hope it would help someone. You can place the SelectedValue property inside your dropdownlist tag like below:
<asp:DropDownList SelectedValue='<% Eval("Country") %>' ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px" Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>

Categories