I have Template Field for gridview as below:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
When i am in gv_RowUpdating event, i wanted to take the value of edited field by findcontrol.
For that i am using following code:
`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
But each time it is showing me null value in txtUname when i debug the code.
What can be the problem?
Full Event Code:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=#eName");
cmd.parameters.AddParametersWithValue("#eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
EDIT
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
refer this
http://www.codeproject.com/Articles/37207/Editable-Gridview-with-Textbox-CheckBox-Radio-Butt
also put your code for Edit command. it might be RowEditing or RowCommand
Related
I am working on a project in which I am to display, insert, delete the data in my access database. I made buttons that will display a specific table from the database. I then made an asp column to display the delete button next to each row. The issue that I am trying to figure out is: How can I have it so that when the delete button is clicked the specific row is identified so then I may delete it? Any hints or tips are welcomed. Thank you.
<body>
<h1 class="center" style="text-align: center" >Display, Delete, and Add</h1>
<h3 id="Title1"></h3>
<style>
.center{
margin: 0 auto;
}
</style>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" class="center" runat="server" Width="300px" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
</p>
<p >
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Courses" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Student Information" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Students" />
</p>
<p>
</p>
<p>
</p>
<p>
</p>
</form>
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con = new OleDbConnection (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\achowdhary\Documents\Database1.accdb");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM COURSES", con);
DataSet set = new DataSet();
ada.Fill(set, "COURSES");
DataTable tab = new DataTable();
tab = set.Tables["COURSES"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENT_INFO", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENT_INFO");
DataTable tab = new DataTable();
tab = set.Tables["STUDENT_INFO"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENTS", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENTS");
DataTable tab = new DataTable();
tab = set.Tables["STUDENTS"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void btn1_Click(object sender, EventArgs e)
{
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "hello" + "');", true);
}
}
Many possibilites, my prefer is, bind a commandArgument in button with your identifier, and recover this value on post back
protected void btn1_Click(object sender, EventArgs e)
{
var identifier = ((Button)sender).CommandArgument;
}
Html
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click" CommandArgument='<%# Eval("PropertyName") %>'/>
</ItemTemplate>
I've got a gridview, which each row have a edit and a delete button.
I've managed to put my edit button working, but not the delete button.
Here's my aspx:
<asp:GridView ID="gvfaq" runat="server" AutoGenerateColumns="false" DataKeyNames="faq_id" OnRowDataBound="gvfaq_RowDataBound" OnRowCommand="gvfaq_RowCommand" OnRowDeleting="gvfaq_RowDeleting" >
<Columns>
<asp:BoundField ItemStyle-Width="100px" DataField="text" HeaderText="Text" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="editbutton" CommandArgument='<%# Eval("faq_id") %>' CommandName="Edit" Text="Edit" />
<asp:Button runat="server" ID="delbutton" CommandArgument='<%# Eval("faq_id") %>' CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this is my code behind:
protected void gvfaq_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int ID = Convert.ToInt32(e.CommandArgument);
DeleteFAQ(ID);
}
}
protected void gvfaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button l1 = (Button)e.Row.FindControl("editbutton");
l1.Attributes.Add("onclick", "Javascript:suport(" + l1.CommandArgument.ToString() + ");return false;");
l1.Attributes.Add("onClientClick", "Javascript:suport(" + l1.CommandArgument.ToString() + ");return false;");
Button l2 = (Button)e.Row.FindControl("delbutton");
l2.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete this record?')");
l2.Attributes.Add("onClientClick", "javascript:return confirm('Are you sure you want to delete this record?')");
}
}
protected void gvfaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gv = (GridView)this.FindControl("gvfaq");
int ID = (int)gv.DataKeys[e.RowIndex].Value;
DeleteFAQ(ID);
}
protected void DeleteFAQ(int ID)
{
using (SqlCommand myCommand = new SqlCommand())
using (SqlConnection myServerCreate = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ServerCreate"].ConnectionString))
{
myServerCreate.Open();
myCommand.Connection = myServerCreate;
myCommand.CommandText = "delete from faq where faq_id = " + ID;
myCommand.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(Page, typeof(Page), "Close", "__doPostBack('','Delete');", true);
}
The strange, is that I have another page, from where I copied/rearragend this code, and there is working fine.
Thanks.
UPDATE
If I check the html generated on the other page button, this code is added, which doesn't succeed in this:
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$gvDocuments$ctl02$delbutton", "", true, "", "", false, false))
I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</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 delete these images?')">
<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"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
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 +")"
I have made an database application. At the moment i have a add and delete function, but now i am searching for help with the update function. I have searched all over this website for an answer, but no luck i guess. So what i want is that if i click on a record in the ListView that it automatically shows up in the textboxes so that i can change things, and when i click the button "Update" it has to update the record.
Help will be extremely appreciated!
my code of Form1
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=E:\Users\Ali\Documents\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", textBox1.Text);
cmd.Parameters.AddWithValue("#query", textBox2.Text);
cmd.Parameters.AddWithValue("#email", textBox3.Text);
cmd.Parameters.AddWithValue("#subject", textBox4.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown update listview
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
button3.Enabled = true;
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE principalID = #principalID", conn);
cm.Parameters.AddWithValue("#principalID", listView1.SelectedItems[0].Text);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void button2_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
Form2 form2 = new Form2();
form2.Show();
form2.PrincipalID = principalid;
form2.Query = query;
form2.Email = email;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
Why are you using listview.You can use datagridview instead.You can bind the database file with datagridview which would create update,select and insert command itself.
I don't see why you cannot do so. It's relatively easy in listview to update an item.
You need to create EditItemTemplate, for your ListView, so that textboxes appear in your row to be edited.
you can handle this in ItemEditing event.
and then you handle update through ItemUpdating event of ListView.
below am posting a sample example: it might help you out:
create your ListView markup like this:
<asp:ListView ID="lvwTest" runat="server" OnItemDeleting="lvwTest_ItemDeleting" OnItemEditing="lvwTest_ItemEditing"
OnItemUpdating="lvwTest_ItemUpdating">
<LayoutTemplate>
<table>
<tr>
<td>
Column1
</td>
<td>
Column2
</td>
<td>
Column3
</td>
<td>
Action
</td>
</tr>
<tr id="itemplaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lbl1" runat="server" Text='<%#Eval("col1") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("col2") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("col3") %>'></asp:Label>
</td>
<td>
<asp:Button ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="txt1" runat="server" Text='<%#Bind("col1") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt2" runat="server" Text='<%#Bind("col2") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt3" runat="server" Text='<%#Bind("col3") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnUpdate" CommandName="Update" Text="Update" runat="server" />
<asp:Button ID="btnCancel" CommandName="Cancel" Text="Cancel" runat="server" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
so basically you've created EditItemTemplate.
See how ItemTemplate has a button "btnEdit" in the last column and EditItemTemplate has two buttons "btnUpdate" and "btnCancel" instead of that with appropriate CommandName.
now here are your events:
ItemEditing:
protected void lvwTest_ItemEditing(object sender, ListViewEditEventArgs e)
{
lvwTest.EditIndex = e.NewEditIndex;
}
ItemUpdating:
protected void lvwTest_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
TextBox txt = (lvwTest.Items[e.ItemIndex].FindControl("txt1")) as TextBox;
//as above find othe textboxes as well/
//create your update query
//SqlCeCommand cmd = new SqlCeCommand(updateQuery, cn);
//and rest of the syntax
lvwTest.EditIndex = -1;
BindGrid();
}
your datasource:
public void BindGrid()
{
DataTable db = new DataTable();
db.Columns.Add("col1");
db.Columns.Add("col2");
db.Columns.Add("col3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
lvwTest.DataSource = db;
lvwTest.DataBind();
}
inside page's Page_Load
if (!IsPostBack)
BindGrid();