I'm using gridview with edit and delete button.
When i delete particular row in gridview, it will be removed. but again i reload the page, the deleted row again displayed. I mean, row is not remove in database.
Here is my code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hiddenfield.Value = index.ToString();
Textid.Text = gr.Cells[1].Text;
Textusername.Text = gr.Cells[2].Text;
Textclass.Text = gr.Cells[3].Text;
Textsection.Text = gr.Cells[4].Text;
Textaddress.Text = gr.Cells[5].Text;
}
else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
and asps file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True"
EnablePersistedSelection="True" BackColor="White" EnableViewState="true" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
<ControlStyle BorderColor="#CCFF66" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle BackColor="#FF66FF" />
</asp:GridView>
storedprocedure:
ALTER PROCEDURE StoredProcedure4
(
#id int
)
AS
begin
Delete from Student where id=#id
End
I'm new to .net. can anyone help me to fix this?
Thanks,
Alternative way could be,
Short answer
Pass ID using commandargument
Full answer
Replace
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
By
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Eval("ID") %>' CommandName="Deleterow"></asp:Button>
in aspx and in cs
Replace
else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
By
else if (e.CommandName == "Deleterow")
{
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", Convert.ToInt32(e.CommandArgument));
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
pass parameter not valid #id change #ID
ALTER PROCEDURE StoredProcedure4
(
#ID as int=0
)
AS
begin
Delete from Student where id=#ID
End
Pass Id as command argument in delete button and access on code behind like below.
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
else if (e.CommandName == "Deleterow")
{
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Convert.ToInt32(e.CommandArgument));
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
Related
Here is my aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True" EnablePersistedSelection="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is code behind:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
GridViewRow gr = GridView1.SelectedRow;
gr.Cells[1].Text = Textusername.Text;
gr.Cells[2].Text = Textclass.Text;
gr.Cells[3].Text = Textsection.Text;
gr.Cells[4].Text = Textaddress.Text;
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
The selected row did not select in gridview. May i know how to enable gridview row. I used msdn and other documents and i followed,but nothing helps.
I design i set enable selection, but still i didn't find out issue.
Can anyone help me?
Thanks,
Basically we get SelectedRow of GridView Upon some GridviewRow Action event like OnSelectedIndexChanged , OnSelectedIndexChanging , OnRowEditing or from Template control like Button click. But here in your coding I don't think your btnsub_Click is inside Gridview so If you want to use the SelectedGridViewRow after your GridviewRow Action event then save the index in some temporary variable or pass the variable to method as argument.
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = Gridview1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
OR In OnRowEditing also you can get the index of row
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hidval.Value = index.ToString();
}
}
and on button Click you can get the hiddenfield value as index:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
if(!String.IsNullOrEmpty(hiddenfield.Value))
{
int index = Convert.ToInt16(hiddenfield.Value);
GridView1.Rows[index].Cells[1].Text = Textusername.Text;
GridView1.Rows[index].Cells[2].Text = Textclass.Text;
GridView1.Rows[index].Cells[3].Text = Textsection.Text;
GridView1.Rows[index].Cells[4].Text = Textaddress.Text;
}
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
I am having some issues using a stored procedure in an asp.net webpage
I have created a stored procedure to insert/update and declare product discontinued.
I am getting the following error:
expected parameter no supplied.
I am not sure why. Any help would be amazing as I am really struggling to get my head around the problem
My markup is as follows:
<asp:Label ID="lblProdGrd" runat="server"></asp:Label>
<asp:GridView
ID="grdProds"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdProds_PageIndexChanging"
OnRowCancelingEdit="grdProds_RowCancelingEdit"
OnRowCommand="grdProds_RowCommand"
OnRowEditing="grdProds_RowEditing"
OnRowUpdating="grdProds_RowUpdating">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" FooterText="Product ID" HeaderText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" Text='<%# Eval("ProductId") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblAdd" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Name" HeaderText="Product Name" FooterText="ProductName">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Description" AccessibleHeaderText="Product description" FooterText="Product Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("Description")%>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDescription" runat="server" TextMode="MultiLine"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Price" AccessibleHeaderText="Product Price" FooterText="Product Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Eval("Price") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddPrice" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCat" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstCatEdit" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstCat" runat="server" AppendDataBoundItems="True"
DataTextField='<%# Eval("CategoryName") %>' DataValueField='<%# Eval("CategoryId")%>'>
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub-Category" AccessibleHeaderText="Sub-Category" FooterText="Sub-Category">
<ItemTemplate>
<asp:Label ID="lblSubCat" runat="server" Text='<%# Eval("ProductType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstSubCat" runat="server"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddSubCat" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Image" AccessibleHeaderText="Product Image" FooterText="Product Image">
<ItemTemplate>
<asp:Image ID="imgProd" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstProdImg" runat="server"></asp:DropDownList>
<asp:Image ID="imgProdEdit" runat="server" Height="250" Width="250" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdImg" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item in stock" AccessibleHeaderText="Item in stock" FooterText="Item in stock">
<ItemTemplate>
<asp:CheckBox ID="chkInStock" runat="server" Checked='<%# Eval("InStock") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkInStockEdit" runat="server" Checked='<%# Eval("InStock") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkInStockAdd" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pre-Designed" AccessibleHeaderText="Pre-designed" FooterText="Pre-Designed">
<ItemTemplate>
<asp:CheckBox ID="chkPrePrinted" runat="server" Checked='<%# Eval("PrePrinted") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkPrePrintedEdit" runat="server" Checked='<%# Eval("PrePrinted") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkAddPrePrinted" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView
My code behind is as follows:
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
grdProds.DataSource = ds;
grdProds.DataBind();
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProds.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void grdProds_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdProds.EditIndex = -1;
BindGrid();
}
protected void grdProds_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
TextBox txtName = (TextBox)grdProds.FooterRow.FindControl("txtAddname");
TextBox txtDescription = (TextBox)grdProds.FooterRow.FindControl("txtAddDescription");
TextBox txtPrice = (TextBox)grdProds.FooterRow.FindControl("txtAddPrice");
DropDownList lstCatEdit = (DropDownList)grdProds.FooterRow.FindControl("lstCat");
DropDownList lstSubCat = (DropDownList)grdProds.FooterRow.FindControl("lstAddSubCat");
DropDownList lstImageProd = (DropDownList)grdProds.FooterRow.FindControl("lstAddProdImg");
CheckBox chkInStockEdit = (CheckBox)grdProds.FooterRow.FindControl("chkInStockAdd");
CheckBox chkPrePrinted = (CheckBox)grdProds.FooterRow.FindControl("chkAddPrePinted");
string ProductName, Description, Price, Category, SubCat, Image;
bool InStock, Preprinted;
ProductName = txtName.Text;
Description = txtDescription.Text;
Price = txtPrice.Text;
Category = lstCatEdit.SelectedValue;
SubCat = lstSubCat.SelectedValue;
Image = lstImageProd.SelectedValue;
InStock = chkInStockEdit.Checked;
Preprinted = chkPrePrinted.Checked;
AddProduct(ProductName, Description, Price, Category, SubCat, Image, InStock, Preprinted);
grdProds.EditIndex = -1;
BindGrid();
}
}
protected void AddProduct(string ProductName, string Description, string Price, string Category, string SubCat,
string Image, bool InStock, bool Preprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", "Add"));
cmd.Parameters["#status"].Value = "";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = ProductName;
cmd.Parameters.Add(new SqlParameter("#Description", Description));
cmd.Parameters["#Description"].Value = Description;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = Price;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = Category;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = SubCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = Image;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = InStock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = Preprinted;
try {
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label prId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
string pId = prId.Text;
DeleteProduct(pId);
grdProds.EditIndex = -1;
BindGrid();
}
protected void DeleteProduct(string pId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = pId;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowEditing(object sender, GridViewEditEventArgs e)
{
grdProds.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdProds_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label prdId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
TextBox Name = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtName");
TextBox Description = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Price = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtPrice");
DropDownList Category = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstCatEdit");
DropDownList SubCat = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstSubCat");
DropDownList Image = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstProdImg");
CheckBox InStock = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkInStockEdit");
CheckBox PrePrinted = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkPrePrintedEdit");
string ProdId = prdId.Text;
string eName = Name.Text;
string eDescription = Description.Text;
string ePrice = Price.Text;
string eCat = Category.SelectedValue;
string eSCat = SubCat.SelectedValue;
string eImage = Image.SelectedValue;
bool eInstock = InStock.Checked;
bool ePreprinted = PrePrinted.Checked;
UpdateProduct(ProdId, eName, eDescription, ePrice, eCat, eSCat, eImage, eInstock, ePreprinted);
grdProds.EditIndex = -1;
BindGrid();
}
protected void UpdateProduct(string ProdId, string eName, string eDescription, string ePrice, string eCat, string eSCat, string eImage, bool eInstock, bool ePreprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = ProdId;
cmd.Parameters.Add(new SqlParameter("#Status", "Update"));
cmd.Parameters["#Status"].Value = "Update";
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = eCat;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = eSCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = eImage;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = eInstock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = ePreprinted;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
My stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Products]
-- Add the parameters for the stored procedure here
#ProdId int,
#Category int,
#ProductType tinyint,
#Price money,
#InStock bit = 1,
#ProductName varchar(50),
#Image int,
#Description varchar(max),
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50)
AS
BEGIN
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select p.ProductId,p.ProductName,c.CategoryId,c.CategoryName,
pt.ProductType,pt.ProductTypeId,p.Price,p.InStock,pi.ImagePath,
pi.ImageId,pi.ImageName,p.Description,p.PrePrinted,p.Discontinued
from ProductDetails.Products p
join ProductDetails.Category c on c.CategoryId = p.Category
join ProductDetails.ProductType pt on pt.ProductTypeId = p.ProductType
join ProductDetails.ProductImages pi on pi.ImageId = p.ImageId
where p.Discontinued = 0
end
else if(#Status = 'Update')
begin
update Productdetails.Products
set Category = #Category, ProductType = #ProductType,
Price = #Price, InStock = #InStock, ProductName = #ProductName,
ImageId = #Image, Description = #Description, PrePrinted = #PrePrinted
where ProductId = #ProdId
end
else if(#Status = 'Add')
begin
insert into ProductDetails.Products (Category,ProductType,Price,InStock,ProductName,ImageId,Description,PrePrinted,Discontinued)
values (#Category,#ProductType,#Price,#InStock,#ProductName,#Image,#Description,#PrePrinted,#Discontinued)
end
else if(#Status = 'Delete')
begin
Update ProductDetails.Products
set Discontinued = #Discontinued
where ProductId = #ProdId
end
END
Any help anyone is able to offer me to resolve this would be wonderful as I have been scratching my head for a few days over this and am no closer to resolving the issue. I apologise if I have not provided all the information you may need, please do not hesitate to ask and I will provide.
I think you try to pass only #Status. Am I right? if yes, then in stored procedure, you need to define parameter with default null value which means you may be pass or not the null parameter and .net not give this error.
#ProdId int = null,
#Category int= null,
#ProductType tinyint = null,
#Price money = null,
#InStock bit = 1, --for this you already mention what is default value. so no need to change. Same thing for below.
#ProductName varchar(50) = null,
#Image int = null,
#Description varchar(max) = null,
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50) = null
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();
}
}
}
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.