Hi @Gani_tpt,
The edit row cannot be obtained directly. Perhaps you can try to record EditIndex through Session and assign a value in OnRowDataBound.
Session["EditIndex"] = gvCustomers.EditIndex;
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DropDownList1 = (e.Row.FindControl("ddlCustomers") as DropDownList);
List<Item> items = new List<Item>();
items.Add(new Item() { Value = "1", Text = "USA" });
items.Add(new Item() { Value = "2", Text = "UK" });
items.Add(new Item() { Value = "3", Text = "AUS" });
items.Add(new Item() { Value = "4", Text = "OTHERS" });
DropDownList1.DataSource = items;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
DataRowView dr = e.Row.DataItem as DataRowView;
////ddList.SelectedItem.Text = dr["category_name"].ToString();
//ddList.SelectedValue = dr["category_name"].ToString();
FileUpload fuUpload = (FileUpload)e.Row.FindControl("fuUpload");
fuUpload.Attributes["onchange"] = "UploadFile(this)";
Label label = (e.Row.FindControl("ImageErrorLabel") as Label);
if (Session["FileUpload1"] != null)
{
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
label.Text = Path.GetFileName(file.FileName);
}
Session["EditIndex"] = gvCustomers.EditIndex;
}
}
}
Control control = null;
if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
{
control = gvCustomers.FooterRow;
}
else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
{
control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
All test code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
function UploadFile(fileUpload) {
if (fileUpload.value != '') {
$("[id*=gvCustomers]").find("[id*=btnUpload]").click();
}
}
</script>
<script type="text/javascript">
function checkNumberAndDecimal(val) {
var allowedString = /^\d+(\.\d{0,2})?$/; // Allow 2 decimal place with numeric value
if (allowedString.test(val) == false) {
alert("Allow 2 decimal place with numeric value...! " + val);
$("[id*=gvCustomers]").find("[id*=txtPayAmount]").value = "";
$("[id*=gvCustomers]").find("[id*=txtPayAmount]").focus();
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" ShowFooter="true"
OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating"
OnRowDeleting="OnRowDeleting" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<FooterTemplate>
<asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<%# Eval("Country") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCountry" runat="server" onkeyup="return checkNumberAndDecimal(this.value)"></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DOB">
<ItemTemplate>
</ItemTemplate>
<FooterTemplate>
<div>
<asp:TextBox ID="txtDOB" runat="server" Text=""></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
Format="MM/dd/yyyy" PopupButtonID="btnDate1"
PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
<asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
runat="server" />
</div>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDOB" runat="server" Text=""></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
Format="MM/dd/yyyy" PopupButtonID="btnDate1"
PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
<asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<%# Eval("FileName") %>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Label ID="ImageErrorLabel" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
</FooterTemplate>
<EditItemTemplate>
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Label ID="ImageErrorLabel" runat="server" Text='<%# Eval("FileName") %>' />
<asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="150" />
</Columns>
<EmptyDataTemplate>
<tr>
<th scope="col">Customer Name</th>
<th scope="col">Name</th>
<th scope="col">Country</th>
<th scope="col">DOB</th>
<th scope="col">Upload</th>
<th scope="col"></th>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlCustomers" Width="100px" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtOtherCustomers" Text="" runat="server" Visible="false"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txtName" runat="server" /></td>
<td>
<asp:TextBox ID="txtCountry" runat="server" onkeyup="return checkNumberAndDecimal(this.value)"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txtDOB" CssClass="txtInput" runat="server" Text=""></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDOB"
Format="MM/dd/yyyy" PopupButtonID="btnDate1"
PopupPosition="BottomRight" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>
<asp:ImageButton ID="btnDate1" ImageUrl="~/images/imgCalendar.png"
runat="server" />
</td>
<td>
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Label ID="ImageErrorLabel" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
<table>
<tr>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" />
</td>
</tr>
</table>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
Control control = null;
if (!this.IsPostBack)
{
this.BindGrid();
if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
{
control = gvCustomers.FooterRow;
}
else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
{
control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
TextBox txtDOB = control.FindControl("txtDOB") as TextBox;
txtDOB.Attributes.Add("readonly", "readonly");
FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
fuUpload.Attributes["onchange"] = "UploadFile(this)";
DropDownList DropDownList1 = (control.FindControl("ddlCustomers") as DropDownList);
List<Item> items = new List<Item>();
items.Add(new Item() { Value = "1", Text = "USA" });
items.Add(new Item() { Value = "2", Text = "UK" });
items.Add(new Item() { Value = "3", Text = "AUS" });
items.Add(new Item() { Value = "4", Text = "OTHERS" });
DropDownList1.DataSource = items;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
}
if (this.IsPostBack)
{
if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
{
control = gvCustomers.FooterRow;
}
else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
{
control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
Label label = (control.FindControl("ImageErrorLabel") as Label);
FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
if (Session["FileUpload1"] == null && fuUpload.HasFile)
{
Session["FileUpload1"] = fuUpload.PostedFile;
label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
}
else if (Session["FileUpload1"] != null && (fuUpload.PostedFile.ContentLength < 0))
{
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
label.Text = Path.GetFileName(file.FileName);
}
else if (fuUpload.HasFile)
{
Session["FileUpload1"] = fuUpload.PostedFile;
label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
}
}
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DropDownList1 = (e.Row.FindControl("ddlCustomers") as DropDownList);
List<Item> items = new List<Item>();
items.Add(new Item() { Value = "1", Text = "USA" });
items.Add(new Item() { Value = "2", Text = "UK" });
items.Add(new Item() { Value = "3", Text = "AUS" });
items.Add(new Item() { Value = "4", Text = "OTHERS" });
DropDownList1.DataSource = items;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
DataRowView dr = e.Row.DataItem as DataRowView;
////ddList.SelectedItem.Text = dr["category_name"].ToString();
//ddList.SelectedValue = dr["category_name"].ToString();
FileUpload fuUpload = (FileUpload)e.Row.FindControl("fuUpload");
fuUpload.Attributes["onchange"] = "UploadFile(this)";
Label label = (e.Row.FindControl("ImageErrorLabel") as Label);
if (Session["FileUpload1"] != null)
{
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
label.Text = Path.GetFileName(file.FileName);
}
Session["EditIndex"] = gvCustomers.EditIndex;
}
}
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
gvCustomers.EditIndex = -1;
this.BindGrid();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
gvCustomers.EditIndex = -1;
this.BindGrid();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void Upload(object sender, EventArgs e)
{
Control control = null;
if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
{
control = gvCustomers.FooterRow;
}
else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
{
control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
Label label = (control.FindControl("ImageErrorLabel") as Label);
FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
if (Session["FileUpload1"] == null && fuUpload.HasFile)
{
Session["FileUpload1"] = fuUpload.PostedFile;
label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
SaveFile(file);
}
else if (Session["FileUpload1"] != null && (fuUpload.PostedFile.ContentLength <0))
{
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
label.Text = Path.GetFileName(file.FileName);
SaveFile(file);
}
else if (fuUpload.HasFile)
{
Session["FileUpload1"] = fuUpload.PostedFile;
label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
SaveFile(fuUpload.PostedFile);
}
}
private void SaveFile(HttpPostedFile file)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("~/images/" + fname));
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string query = "SELECT Name, Country,FileName FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
con.Open();
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
con.Close();
}
}
}
}
}
protected void ddlCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
Control control = null;
if (gvCustomers.FooterRow != null && (Convert.ToInt32(Session["EditIndex"]) < 0 || Session["EditIndex"] == null))
{
control = gvCustomers.FooterRow;
}
else if (Session["EditIndex"] != null && Convert.ToInt32(Session["EditIndex"]) >= 0)
{
control = gvCustomers.Rows[Convert.ToInt32(Session["EditIndex"])];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
DropDownList ddlCustomers = (control.FindControl("ddlCustomers") as DropDownList);
TextBox txtOtherCustomers = control.FindControl("txtOtherCustomers") as TextBox;
if (ddlCustomers.SelectedItem.Text == "OTHERS")
{
txtOtherCustomers.Visible = true;
}
else
{
txtOtherCustomers.Visible = false;
}
}
public class Item
{
public Item() { }
public string Value { set; get; }
public string Text { set; get; }
}
protected void Add(object sender, EventArgs e)
{
Control control = null;
if (gvCustomers.FooterRow != null)
{
control = gvCustomers.FooterRow;
}
else if (gvCustomers.EditIndex >= 0)
{
control = gvCustomers.Rows[gvCustomers.EditIndex];
}
else
{
control = gvCustomers.Controls[0].Controls[0];
}
string name = (control.FindControl("txtName") as TextBox).Text;
string country = (control.FindControl("txtCountry") as TextBox).Text;
string txtDOB = (control.FindControl("txtDOB") as TextBox).Text;
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
string filename = Path.GetFileName(file.FileName);
byte[] bytes = null;
if (file != null)
{
BinaryReader br = new BinaryReader(file.InputStream);
bytes = br.ReadBytes((int)file.InputStream.Length);
}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string query = "INSERT INTO Customers VALUES(@Name, @Country,@FileName,@Data,@Data1)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Parameters.AddWithValue("@FileName", filename);
cmd.Parameters.AddWithValue("@Data", bytes);
cmd.Parameters.AddWithValue("@Data1", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.