i'm trying to edit the information of Student table using gridview in c#
but my code updates the gridview without changing the table in my sql database
I don't know where is the problem
Here is my gridview :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="S_ID" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AllowPaging="true" >
<Columns>
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:TextBox ID="S_ID" runat="server" Text='<%# Eval("S_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="S_Name" runat="server" Text='<%# Eval("S_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="S_Email" runat="server" Text='<%# Eval("S_Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="S_Email" runat="server" Text='<%# Bind("S_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
and this is the code behind:
protected void gvbind()
{
SqlConnection conn = new SqlConnection(#"MYCONNECTION");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT S_ID , S_Name , S_Email , B_ID FROM Student", conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt; // now assign this datatable dt to gridview as datasource
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int sUserId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Name"); //give the edititem template ID
TextBox email = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Email");
try
{
SqlConnection conn = new SqlConnection(#"MYCONNECTION");
conn.Open();
SqlCommand c = new SqlCommand("Update Student set S_Name='" + name.Text + "',S_Email='" + email.Text + "'where S_ID='" + sUserId + "'");
c.Connection = conn;
c.ExecuteNonQuery();
GridView1.EditIndex = -1;
gvbind();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(typeof(string), "Key", "alert('Error : \\n" + ex.Message + "');", true);
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gvbind();
}
please can anyone help me why this change the gridview only but not the DB ?!
I think the first problem I've seen in your code is:
SqlCommand c = new SqlCommand("Update Student set S_Name='" + name.Text + "',S_Email='" + email.Text + "'where S_ID='" + sUserId + "'");
if S_ID column in your database is Integer then you shouldn't be using ' character
to indent the parameter sUserId it is just :
where S_ID = " + sUserId +")"
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">
So I tried to added multiple filters for the gridview and I populated the dropdowns with the distinct datas of the column, but it gives me an exception, System.ArgumentException: Parameter 'siteValue' not found in the collection. I've added the mysql stored procedure along with the below code.
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField HeaderText="Agent login">
<ItemTemplate>
<asp:Label ID="lbllogin" runat="server" Text='<%# Eval("agentlogin") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
Site:
<asp:DropDownList ID="ddlgvsite" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblsite" runat="server" Text='<%# Eval("site") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Skill:
<asp:DropDownList ID="ddlgvskill" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblskill" runat="server" Text='<%# Eval("skill") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift">
<ItemTemplate>
<asp:Label ID="lblshift" runat="server" Text='<%# Eval("shift") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TM">
<ItemTemplate>
<asp:Label ID="lbltm" runat="server" Text='<%# Eval("tm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrpM">
<ItemTemplate>
<asp:Label ID="lblGrpM" runat="server" Text='<%# Eval("grpM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OpsM">
<ItemTemplate>
<asp:Label ID="lblOpsM" runat="server" Text='<%# Eval("opsM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave type">
<ItemTemplate>
<asp:Label ID="lbltype" runat="server" Text='<%# Eval("leavetype") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<asp:Label ID="lbldate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lbltime" runat="server" Text='<%# Eval("time") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" ControlStyle-Width="300px">
<ItemTemplate>
<asp:Label ID="lblreason" runat="server" Text='<%# Eval("reason") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below would be the server side codes
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
TableCell cells = gdvTM.HeaderRow.Cells[0];
PopulateDropDown((cells.FindControl("ddlgvsite") as DropDownList), (cells.FindControl("lblsite") as Label).Text);
PopulateDropDown((cells.FindControl("ddlgvskill") as DropDownList), (cells.FindControl("lblskill") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData");
cmd.CommandType = CommandType.StoredProcedure;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#siteValue", ViewState["Site"].ToString());
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#skillValue", ViewState["Skill"].ToString());
}
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Site"] != null ? (string)ViewState["Site"] : string.Empty, cell.FindControl("ddlgvsite") as DropDownList);
setDropdownselectedItem(ViewState["Skill"] != null ? (string)ViewState["Skill"] : string.Empty, cell.FindControl("ddlgvskill") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvsite":
ViewState["Site"] = selectedValue;
break;
case "ddlgvskill":
ViewState["Skill"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT " + columnName + " FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
protected void gdvTM_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvTM.PageIndex = e.NewPageIndex;
this.BindGrid();
}
Below would be the MySql stored procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`
(in siteValue varchar(45), in skillValue varchar(100))
BEGIN
select *
from approved
where site = siteValue or siteValue is null and
skill = skillValue or skillValue is null;
END
Please let me know what I'm doing wrong. Thanks in advance....
1) You have to changes your stored procedure like
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`(in siteValue varchar(45),
in skillValue varchar(100))
BEGIN
IF siteValue IS NULL and skillValue IS NULL THEN
select * from approved;
ELSEIF siteValue IS NULL and skillValue IS NOT NULL THEN
select * from approved where skill = skillValue;
ELSEIF siteValue IS NOT NULL and skillValue IS NULL THEN
select * from approved where site = siteValue;
ELSE
select * from approved where site = siteValue and skill = skillValue;
END IF;
END
2) In your BindGrid function make the changes below
private void BindGrid()
{
//Your rest of code is same here
string siteValue = null;
string skillValue = null;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
siteValue = ViewState["Site"].ToString();
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
skillValue = ViewState["Skill"].ToString();
}
cmd.Parameters.AddWithValue("siteValue", siteValue);
cmd.Parameters.AddWithValue("skillValue", skillValue);
//Your rest of code is same here
}
here i want to have no.of coloumns i have checked and deleted in lable
i have used following code to execute my query of deleting multiple values in gridview using checkbox
here is my code and script part
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
grd_bnd();
}
}
private void grd_bnd()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from student", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
grd_bnd();
}
}
and here is script
<asp:GridView ID="GridView1" runat="server" DataKeyNames="rollno" AllowSorting="true" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkboxdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat ="server" Text='<%#Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No.">
<ItemTemplate>
<asp:Label ID="lblrollno" runat ="server" Text='<%#Eval("rollno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="lblbatch" runat ="server" Text='<%#Eval("batch") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblcourse" runat ="server" Text='<%#Eval("course") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
<asp:Button ID="Button3" runat="server" Font-Bold="True" Text="Delete Selected" ForeColor="#000066" OnClick="Button3_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="#666666"></asp:Label>
i wanna get the number of entities deleted in above lable , lable1.
Simply add a count before your loop
protected void Button3_Click(object sender, EventArgs e)
{
int rows = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
rows += cmd.ExecuteNonQuery(); //Can return 0 if no rows were deleted!
con.Close();
cmd.Dispose();
}
}
grd_bnd();
MessageBox.Show(String.Format("Rows affected {0}", rows);
}
You can use the return value of ExecuteNonQuery:
int numDeleted = cmd.ExecuteNonQuery();
MSDN: returns the number of rows affected.
If you want the total rows use a variable:
int totalNumDeleted = 0;
foreach (GridViewRow row in GridView1.Rows)
{
// ...
int numDeleted = cmd.ExecuteNonQuery();
totalNumDeleted += numDeleted;
}
Label1.Text = string.Format("{0} students were deleted successfully.", totalNumDeleted);
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();
}
}
}