dynamically add itemplate to the gridview - c#

I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help

Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.

Related

how to get column data when check box is checked using data list in asp.net

this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.

Show Table when SelectedValue of DropDownList is true C#

I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?
Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}
refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.

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

Change gridview header text when i choose dropdownlist

I have some doubt
This is my coding for aspx page and .cs page
How can I achieve the following
If i select February the header text assigned January value and i select march then assign February value...Could you please help me find a solution for it
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="8-14">
<ItemTemplate>
<asp:TextBox ID="TxtWeek2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .CS page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select");
DropDownList1.Items.Add("January");
DropDownList1.Items.Add("February");
DropDownList1.Items.Add("March");
DropDownList1.Items.Add("April");
DropDownList1.Items.Add("May");
SqlConnection cn = new SqlConnection("Data Source=192.169.10.22;Initial Catalog=SHRICITYUNO;User ID=uno;Password=uno");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd = new SqlCommand("SELECT Week1 FROM Finman_FundPlan", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedItem.Text.ToString();
if (DropDownList1.SelectedItem.Text == "January")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "February")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "-";
}
else if (DropDownList1.SelectedItem.Text == "March")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "April")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-30";
}
else if (DropDownList1.SelectedItem.Text == "May")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
}
you can do it using Javascript at client side.
if you observe the grid view then you can notice that row[0] is the header row for gridview.
now you can check decide the which cell test you have to change.
see the following javascript function to accomplish your task
<script language="Javascript">
function ChangeHeaderText()
{
var gridObject = document.getElementById("Gridview1");
gridObject.rows[0].cells[0].innerText = 'NewHeader Text';
return false;
}
</script>
//call above function on 'onchange' event of dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange = "return ChangeHeaderText()"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Try this It will work......

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