The sorting works fine when u fill the gridview using SQL datasource in the aspx page...
but now i am using template field and the columns are filled separately in the codebehind and the sorting is not working...
my code is
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
ondatabound="GridView1_DataBound"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="File Name" ItemStyle-Width="40%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Failure Count" ItemStyle-Width="10%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns></GridView>
and my codebehind is:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT FileName,FailureCount from Files where MachineID=#strID , connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("strID", strID);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string nameoffiles = dt.Rows[i]["FileName"].ToString();
buFailureCode.Add(code);
string count = dt.Rows[i]["BuFailureCount"].ToString();
buFailureCount.Add(count);
}
}
connection.Close();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (namesOfFiles.Count != 0)
{
for (int i = 0; i < namesOfFiles.Count; i++)
{
GridViewRow myRow = GridView1.Rows[i];
Label Label1 = (Label)myRow.FindControl("Label1");
Label Label3 = (Label)myRow.FindControl("Label3");
Label1.Text = namesOfFiles[i].ToString();
Label3.Text = buFailureCount[i].ToString();
}}}
set SortExpression
I think you'll have to handle the OnSorting event and do the actual sorting yourself in code-behind. The API documentation has an example.
Related
i am stuck in a situation where i need to add pagination to parent gridview only(I have a nested gridview where i don't want to add paginatiion to child gridview).i have searched for many example but however I couldn't find any solution.Please help me with this. I am stuck on this issue and could not find any workaround.i am getting input string was not in correct format error on rowcommand event on line
int id = int.Parse(e.CommandName.ToString());
<asp:GridView ID="GVLeader" runat="server" AutoGenerateColumns="false"
DataKeyNames="id" OnRowCommand="GVLeader_RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "15" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Eval("Name") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Detail View" ControlStyle-
BackColor="#EBEBEB">
<ItemTemplate>
<asp:Button runat="server" ID="btnplus" Text="Edit Details"
CssClass="greenButton" CommandName='<%#Eval("id") %>'
CommandArgument='<%#Container.DataItemIndex%>' />
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Salary" >
<ItemTemplate>
<asp:Label ID="lblEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Address " >
<ItemTemplate>
<asp:Label ID="lblEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind Code:-
namespace Final
{
public partial class test : System.Web.UI.Page
{
SqlConnection con = new
SqlConnection(ConfigurationSettings.AppSettings["server"].ToString());
SqlConnection con1 = new SqlConnection("confidential"); //Create
sqlconnection
SqlDataAdapter da;
DataTable dt2, dt1;
Properties objlog = new Properties();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGVLeader();
}
}
protected void GVLeader_RowCommand(object sender,
GridViewCommandEventArgs e)
{
int id = int.Parse(e.CommandName.ToString());
int rowindex = int.Parse(e.CommandArgument.ToString());
GridView GVMember =
(GridView)GVLeader.Rows[rowindex].FindControl("GVMember");
Button btn =
((Button)GVLeader.Rows[rowindex].FindControl("btnplus"));
if (btn.Text == "Edit Details")
{
btn.Text = "Cancel";
GVMember.DataSource = LoadGVMember(id);
GVMember.DataBind();
GVMember.Visible = true;
}
else
{
btn.Text = "Edit Details";
GVMember.Visible = false;
}
}
public void LoadGVLeader()
{
da = new SqlDataAdapter("select * from emptable", con);
dt = new DataTable();
da.Fill(dt);
GVLeader.DataSource = dt;
GVLeader.DataBind();
}
protected DataTable LoadGVMember(int id)
{
da = new SqlDataAdapter("select * from emptable where ID=" + id,
con);
dt1 = new DataTable();
da.Fill(dt1);
ViewState["dt"] = dt1;
return dt1;
}
protected void GVMember_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = e.NewEditIndex;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
int id1 = int.Parse(Gv.DataKeys[e.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
Label lbldeleteid = (Label)gvrow.FindControl("lblID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM emptable where ID='" +
Convert.ToInt32(GVLeader.DataKeys[e.RowIndex].Value.ToString()) + "'",
con);
cmd.ExecuteNonQuery();
con.Close();
LoadGVLeader();
}
}
}
remove pagination props from child grid(GVMember)
change
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
with
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" AlternatingRowStyle-
CssClass="alt" AllowSorting="true">
I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FRACCIONES">
<EditItemTemplate>
<asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLAVE SAT">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Below is the code sample for binding the grid in code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string query;
string countid = " ";
SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
llenagrid();
IncrementoID();
}
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
IncrementoID();
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Agregar_Click(object sender, ImageClickEventArgs e)
{
connStr.Open();
GridViewRow row = GridView1.FooterRow;
TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
SqlCommand com = new SqlCommand(str,connStr);
int count = Convert.ToInt32(com.ExecuteScalar());
connStr.Close();
if (count > 0)
{
string script = "alert('Este Nombre ya Existe.','AtenciĆ³n');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
}
else
{
connStr.Open();
TextBox txtID = (TextBox)row.FindControl("txtAddID");
CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
TextBox txtClave = (TextBox)row.FindControl("txtClave");
string ID = txtID.Text;
string Nombre = txtNombre.Text;
bool Fracc = chkFracc.Checked;
string clave = txtClave.Text;
string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
SqlCommand cmd2 = new SqlCommand(query2, connStr);
cmd2.ExecuteNonQuery();
connStr.Close();
llenagrid();
IncrementoID();
}
}
public void IncrementoID()
{
//query = "select Count(id_unidad) from unidades";
//con.Open();
//SqlCommand cmd = new SqlCommand(query, con);
//string cid = cmd.ExecuteScalar().ToString();
//con.Close();
//TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
//ID.Text = countid + (int.Parse(cid) + 1);
//ID.ReadOnly = true;
con.Open();
SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
SqlDataReader rd = cmd.ExecuteReader();
TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
if (rd.Read())
{
string Value = rd[0].ToString();
if (Value == "")
{
txtID.Text = "1";
}
else
{
txtID.Text = rd[0].ToString();
txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
}
}
con.Close();
}
}
As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.
Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
//IncrementoID(); // Remove the function call from here
GridView1.DataSource = table;
GridView1.DataBind();
IncrementoID(); // Call the function after GridView got binded.
}
I have a nested gridiview inside a repeater :
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SDSRepeaterCity" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td ><label style="color:black; font-size:20px;"><%#Eval("nome_citta") %></label></td>
<td style="display:none;"><asp:Label ID="lblIdCity" runat="server" Text='<%#Eval("id_citta") %>' ></asp:Label></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False"
CssClass="Grid"
EmptyDataText="Nessun risultato corrispondono alla sua ricerca"
ShowHeaderWhenEmpty="True" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="TipoServizio" HeaderText="TipoServizio" />
<asp:BoundField ItemStyle-Width="33%" DataField="Tipologia" HeaderText="Tipologia" />
<asp:TemplateField>
<HeaderTemplate>Prezzo di base</HeaderTemplate>
<ItemTemplate >
<asp:TextBox ID="TBPrezzo" style="text-align:center;font-size:14px;" runat="server" Text=""></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
<HeaderStyle Width="150px" />
</asp:TemplateField>
<asp:BoundField DataField="tipo_macchina" ItemStyle-CssClass="hide" HeaderStyle-CssClass="hide" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="tipo_macchina" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblGvIdCity" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
And a button update with the following code:
TraifRegBLL trigis = TraifRegBLL.Instance;
string strConnString1 = "connexion";
using (SqlConnection con = new SqlConnection(strConnString1))
{
using (SqlCommand cmd = new SqlCommand())
{
String id_aff = Session["id_affiliato"].ToString();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM TarifSMReg WHERE id_affiliato= #Codice ";
cmd.Parameters.AddWithValue("#Codice", id_aff);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
//Add new inseriment
for (int i = 0; i < Repeater1.Items.Count; i++)
{
GridView gvCustomers = Repeater1.Items[i].FindControl("gvCustomers") as GridView;
for (int j = 0; j < gvCustomers.Rows.Count; j++)
{
Label lblGvIdCity = gvCustomers.Rows[j].FindControl("lblGvIdCity") as Label;
GridView gvOrders = gvCustomers.Rows[j].FindControl("gvOrders") as GridView;
for (int k = 0; k < gvOrders.Rows.Count; k++)
{
TextBox TBPrezzo = gvOrders.Rows[k].FindControl("TBPrezzo") as TextBox;
if (String.IsNullOrEmpty(TBPrezzo.Text)==true) { TBPrezzo.Text = "0"; }
if (Convert.ToDouble(TBPrezzo.Text) > 0)
{
TarifSMReg t = new TarifSMReg();
t.id_citta = lblGvIdCity.Text;
t.id_affiliato = Session["id_affiliato"].ToString();
t.tipologia_macchina = gvCustomers.Rows[j].Cells[2].Text;
t.TipoServizio = gvOrders.Rows[k].Cells[0].Text;
t.Tipologia = gvOrders.Rows[k].Cells[1].Text;
t.PrezzoBaseRG = Convert.ToDouble(TBPrezzo.Text.Replace(",", "."));
trigis.addTarifReg(t);
}
}
}
}
here is the result if i insert the price the first time:
but if i update the price will be duplicated like
this.
Can anyone explain me why?
thank you
I have created this gridview .This is my code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
here's my html gridview code
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" Font-Bold="True" Font-Italic="False" Font-Size="Small" Height="72px" style="margin-left: 41px; margin-top: 108px" Width="783px" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="OnRowDataBound">
<AlternatingRowStyle BackColor="#FFFFCC" BorderColor="#FF9900" Wrap="False" />
<Columns>
<asp:TemplateField HeaderText="TASK ID" SortExpression="TASK ID" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="TASKID" runat="server" Text='<%#Eval("[TASK ID]") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NATURE OF PAYMENT" SortExpression="NATURE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="NOP" runat="server" Text='<%#Eval("[NATURE OF PAYMENT]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownnop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DESC" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DESC" Text='<%#Eval("[DESC]") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID ="DESC" runat="server" Text='<%#Eval("[DESC]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="REQUIREDFIELDVALIDATORDESC" runat="server" ControlToValidate="DESC" ErrorMessage="FIELD CANNOT BE EMPTY"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FREQUENCY" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="FREQUENCY" Text='<%#Eval("FREQUENCY") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownfreq"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOP" Text='<%#Eval("PREALERT1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF SUBMISSION OF RETURN" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOSOR" Text='<%#Eval("PREALERT2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddosor"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="OWNER" Text='<%#Eval("OWNER") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownowner"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VERIFICATION OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="VO" Text='<%#Eval("[VERIFICATION OWNER]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownvo"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="STATUS" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="STATUS" Text='<%#Eval("STATUS") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat ="server" ID="dropdownstatus">
<asp:ListItem Text="Active" Value="1"></asp:ListItem>
<asp:ListItem Text="Inactive" Value="0"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false" HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="ID" Text='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="4" />
</asp:GridView>
So, my problem here is that Iam able to edit is using the edit events but I am not able to
populate the dropdown inside the gridview, whereas Iam able to do the same outside the GridView.
Here's my full codebehind
{
Comp obj6 = new Comp();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate gridview
TextBox2.Focus();
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
{
// populate dropdownlist for prealert 1
for (int i = 0; i <= 30; i++)
{
DropDownList3.Items.Insert(i, new ListItem((i + 1).ToString(), (i + 1).ToString()));
}
DropDownList3.DataBind();
}
{
// populate dropdown list for prealert 2
for (int j = 0; j <= 30; j++)
{
DropDownList4.Items.Insert(j, new ListItem((j + 1).ToString(), (j + 1).ToString()));
}
DropDownList4.DataBind();
}
{
//populate dropdown for Nature of Payment
string query = "select * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';";
string columnname = "DESC";
string datavaluefield = "DESC";
obj6.PopulateCombo(DropDownList1, query, columnname, datavaluefield);
}
{
//populate dropdown for frequency
string query1 = "select * from Compliance_Tracker.dbo.frequencyMaster where STATUS='1';";
string columnname1 = "DESC";
string datavaluefield1 = "DESC";
obj6.PopulateCombo(DropDownList2, query1, columnname1, datavaluefield1);
}
{
//populate dropdown for owner
string query2 = "select * from Compliance_Tracker.dbo.ownerMaster where STATUS='1';";
string columnname2 = "NAME";
string datavaluefield2 = "NAME";
obj6.PopulateCombo(DropDownList5, query2, columnname2, datavaluefield2);
}
{
//populate dropdown for owner verification
string query3 = "select * from Compliance_Tracker.dbo.verificationMaster where STATUS='1'";
string columnname3 = "NAME";
string datavaluefield3 = "NAME";
obj6.PopulateCombo(DropDownList6, query3, columnname3, datavaluefield3);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "insert into Compliance_Tracker.dbo.tasklistManager([NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],STATUS)values('" + DropDownList1.SelectedItem.Text + "','" + TextBox2.Text + "','" + DropDownList2.SelectedItem.Text + "','" + DropDownList3.SelectedItem.Text + "','" + DropDownList4.SelectedItem.Text + "','" + DropDownList5.SelectedItem.Text + "','" + DropDownList6.SelectedItem.Text + "','" + DropDownList7.SelectedValue + "');";
obj6.ExecuteScalar(query);
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
TextBox2.Text = string.Empty;
DropDownList7.SelectedItem.Text = "Active";
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string query = "delete Compliance_Tracker.dbo.tasklistManager where Compliance_Tracker.dbo.tasklistManager.ID = " + ID;
string populatequery = query + ";select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.BindGridData(populatequery, GridView1);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
}
And here's the fetchdata code
public DataTable Fetchdata(string strSQL)
{
SqlDataAdapter DAdpt = new SqlDataAdapter();
DataSet DSet = new DataSet();
try
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
DAdpt = new SqlDataAdapter(strSQL, Conn);
DAdpt.Fill(DSet);
return DSet.Tables[0];
}
catch (Exception Ex)
{
return null;
throw new Exception(Ex.Message);
}
finally
{
DAdpt.Dispose();
DSet.Dispose();
Conn.Close();
}
}
Must be some problem with find control code. Try the one I have using in the code given below :
protected void GrdPDataEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Replace your find corntrol code with this
DropDownList drpnop = (DropDownList)e.Row.FindControl("dropdownnop");
if (drpnop != null)
{
drpnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
drpnop.DataTextField = "DESC";
drpnop.DataValueField = "DESC";
drpnop.DataBind();
}
}
}
You can't directly access the DropDownList inside of the GridView while the gridview is being generated. What you'll have to do is to use the GridView OnRowCreated event and populate the dropdown that way. I don't have any sample code handy, but there are a ton of references on the internet.
Most of your code is usable, but you'll need to move a few things around.
Basically you'll need to create an event for OnRowCreated and then - this is the key part - use the FindControl method to find the DropDownList and finally insert the items into the DDL.
Clarification: I thought your code in the OnLoad was trying to populate the DDL and I didn't see the code box scrolled down. Looks like your code is solid, I think you just need to switch from OnRowBinding to OnRowCreated
What I want to achieve is when I click on edit, the Blogtype field in the gridview will be changed to dropdownlist. And Since my database have 3 data in the blogtype which is community work, competition and overseas experience. The dropdownlist will be allows me to select either of these three. After choosing either of this one, and I clicked update, it will be updated in the database. How to do it as I have error in the 3rd screenshot.The name of my dropdownlist for blogtype field is ddlBlogType. help
But for my current code, after clicking edit, it will come out this error. 'ddlBlogType' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Source Code
<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="1000px" Height="147px" AutoGenerateColumns="False"
onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing"
onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID"
onrowdeleting="grdBlog_RowDeleting" AllowPaging="True"
onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3" CellSpacing="1" GridLines="None" >
<Columns>
<asp:BoundField DataField="BlogID" HeaderText="BlogID" ReadOnly="true"
SortExpression="BlogID" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="80px" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" Width="80px" Text='<%# Bind("BlogType") %>'></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="80px" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateEntry" HeaderText="Date Entry" ReadOnly="true" />
<asp:TemplateField HeaderText="Blog Story">
<EditItemTemplate>
<asp:TextBox ID="txtBlogStory" runat="server" TextMode="multiline" rows="10" Text='<%# Bind("BlogStory") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("BlogStory") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="modifiedby" HeaderText="Last Modified By" ReadOnly="true" />
<asp:BoundField DataField="modifieddate" HeaderText="Last Modified Date" ReadOnly="true" />
<asp:CommandField ShowEditButton="True" CausesValidation="false" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
Code Behind Code
if (Page.IsPostBack == false)
{
bindResultGridView();
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
String SQL = null;
SQL = "SELECT BlogID, Name, Blogtype, Description, convert(varchar,Dateentry, 103) as Dateentry, BlogStory, modifiedby, convert(varchar,modifieddate, 103) as modifieddate FROM [EntryTable] ORDER BY BlogID DESC";
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdBlog.DataSource = dt;
grdBlog.DataBind();
reader.Close();
}
finally
{
con.Close();
}
}
protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdBlog.EditIndex = -1;
bindResultGridView();
}
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
/*
DateTime datDate;
*/
/*
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
*/
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, strBlogStory);
/*
}
else
{
lblError.Visible = true;
lblError.Text = "Invalid Date";
lblSuccess.Visible = false;
}
*/
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strBlogStory)
{
try
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [ModifiedBy]=#Modifier, [ModifiedDate] = GETDATE(), [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID";
/*string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
/*string strCommandText = "UPDATE EntryTable SET [ModifiedBy] = [Name], [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
//cmd.Parameters.AddWithValue("#DateEntry", datDate);
cmd.Parameters.AddWithValue("#Description", strDescription);
cmd.Parameters.AddWithValue("#BlogStory", strBlogStory);
cmd.Parameters.AddWithValue("#Modifier", Session["Username"]);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblSuccess.Visible = true;
lblSuccess.Text = "Record updated!";
lblError.Visible = false;
}
else
{
lblSuccess.Visible = true;
lblError.Text = "Update fail";
lblError.Visible = false;
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
catch
{
lblError.Visible = true;
lblError.Text = "Invalid Data";
lblSuccess.Visible = false;
}
}
Did it using the edited code below
Source Code
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" DataTextField="ddlBlogType" DataValueField="ddlBlogType" SelectedValue='<%# Eval("blogType") %>'>
<asp:ListItem Enabled="true" Text="Community Work" Value="Community Work"></asp:ListItem>
<asp:ListItem Text="Competition" Value="Competition"></asp:ListItem>
<asp:ListItem Text="Overseas Experience" Value="Overseas Experience"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Code behind Code
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.SelectedValue;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
}
I see the issue as the way you populate the DropDownList. The code isn't shown in your post, so assuming you don't have anything to that effect.
So you normally set the desired gridviewrow in edit mode as below:
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
Now we need to figure when exactly to bind the dropdownlist. Therefore when the particular datarow (which is in edit mode) is getting databound we have a chance to obtain the reference to the corresponding edit row's dropdownlist. Hence for this you can refer this post.
In summary you need to handle the DataBound event of the gridview and determine from its rowstate what mode it is in. Sharing the code sample from linked post below:
protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("DStatusEdit");
//bind dropdownlist
DataTable dt = con.GetData("select distinct status from directory");
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";
ddList.DataValueField = "YourCOLName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["YourCOLName"].ToString();
}
}
}