issue with populating dropdownlist in gridview edit mode in c# - 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>

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).

dynamically add itemplate to the gridview

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.

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.

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......

Categories