This code re-initialize ListBox1 when append new item after Savepnusers complete successfully.
Writing value in TextBox this value is appended on the ListBox1.
But I can't get all values or single value from ListBox1 to ListBox2, because the append new item disappears from ListBox1.
Please see this:
My complete code below.
Any suggestions?
.cs page
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Threading;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
string sql;
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
protected void btn4_Click(object sender, EventArgs e)
{
while (ListBox2.Items.Count != 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
protected void btn3_Click(object sender, EventArgs e)
{
arraylist2 = new ArrayList();
if (ListBox2.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (!arraylist2.Contains(ListBox2.Items[i]))
{
arraylist2.Add(ListBox2.Items[i]);
}
}
}
for (int i = 0; i < arraylist2.Count; i++)
{
if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
{
ListBox1.Items.Add(((ListItem)arraylist2[i]));
}
ListBox2.Items.Remove(((ListItem)arraylist2[i]));
}
ListBox1.SelectedIndex = -1;
}
}
protected void btn2_Click(object sender, EventArgs e)
{
while (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
arraylist1 = new ArrayList();
if (ListBox1.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]);
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
}
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = #String.Format(" SELECT NAME FROM `country` GROUP BY `NAME` ORDER BY SURFACEAREA DESC LIMIT 10; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "NAME";
ListBox1.DataValueField = "NAME";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = #String.Format("INSERT INTO `stored` SELECT Name, NULL FROM Country WHERE Name=?;");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MTListBox1();
}
}
}
.aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"
EnableEventValidation="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=imgsave]").bind("click", function () {
var qString = "?" + window.location.href.split("?")[1];
var nnewuser = {};
nnewuser.txuser = $("[id*=txuser]").val();
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "Default.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("OK");
alert(JSON.stringify(nnewuser));
if (txtUser) {
$("[id*=ListBox1]").append("<option value='" + nnewuser.txuser + "'>" + nnewuser.txuser + "</option>");
}
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="align-content: center;">
<br />
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<br />
<asp:ImageButton ID="imgsave" runat="server"
ImageUrl="/ImgFolder/Img.gif"
OnClientClick="if (!confirm('Are you sure?')) return false;" />
<br />
LISTBOX1
<br />
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
LISTBOX2
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
</div>
<br />
<div style="align-content: center;">
<asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
<br />
<asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
<br />
<asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
<br />
<asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
</div>
</div>
</form>
</body>
</html>
According to your description and codes,as far as I think,the problem is when you click the button,the page will be refresh and the listbox coudn't get the current data.
I suggest you could use button click to insert data to database intead of ajax.
More details, you could refer to below codes:
<form id="form1" runat="server">
<div style="align-content: center;">
<br />
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<br />
<asp:Button ID="imgsave" runat="server"
OnClientClick="return confirm('Are you sure?');" OnClick="imgsave_Click" />
<br />
LISTBOX1
<br />
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
LISTBOX2
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
</div>
<br />
<div style="align-content: center;">
<asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
<br />
<asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
<br />
<asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
<br />
<asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
</div>
</div>
</form>
Code-behind:
string sql;
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MTListBox1();
}
}
protected void btn1_Click(object sender, EventArgs e)
{
arraylist1 = new ArrayList();
if (ListBox1.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]);
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
}
protected void btn2_Click(object sender, EventArgs e)
{
while (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void btn3_Click(object sender, EventArgs e)
{
arraylist2 = new ArrayList();
if (ListBox2.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (!arraylist2.Contains(ListBox2.Items[i]))
{
arraylist2.Add(ListBox2.Items[i]);
}
}
}
for (int i = 0; i < arraylist2.Count; i++)
{
if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
{
ListBox1.Items.Add(((ListItem)arraylist2[i]));
}
ListBox2.Items.Remove(((ListItem)arraylist2[i]));
}
ListBox1.SelectedIndex = -1;
}
}
protected void btn4_Click(object sender, EventArgs e)
{
while (ListBox2.Items.Count != 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
protected void MTListBox1()
{
string str, strSql;
str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
SqlConnection conn = new SqlConnection(str);
strSql = "select Name from stored";
SqlCommand cmd = new SqlCommand(strSql, conn);
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "NAME";
ListBox1.DataValueField = "NAME";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (Exception ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
public class pnnusers
{
public string txuser { get; set; }
}
protected void imgsave_Click(object sender, EventArgs e)
{
string sql = "INSERT INTO stored(Name) values(#param1)";
string str;
str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
SqlConnection conn = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddWithValue("param1", txuser.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
MTListBox1();
}
Result:
Related
I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help
Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.
I'm stuck with a problem where i can't get the values of any control not just textboxes in button click event so here is the scenario, You can skip it and just can look into my button click event
Page product is performing 2 operations
Create
Update
When a user clicks Edit on GridView in updpage It will redirects it to Product Page to update, Same page is performing Create product operation too, So when I receive QueryString value I'll update the product table and when I won't so I just perform Create operation.
Now I'm stuck when there is no QueryString value so textboxes are updating with a new values but when there is, so they don't give me a new value.
Here is my code
On pageLoad Event I'm filling text boxes with there respective values
where there is an update operation
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
}
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Button event code
protected void btn_Insert_Click(object sender, EventArgs e)
{
getpicture();
SqlCommand cmd;
string pathimage ="";
if (pathimage == "")
{
pathimage = product_image.ImageUrl;
}
else
{
pathimage = ViewState["pathimage"].ToString();
}
if (Request.QueryString["update"] != null)
{
int id = int.Parse(Request.QueryString["update"]);
string query = "UPDATE Products SET product_name=#PRODUCTNAME,price=#PRIZE,unit=#UNIT,product_image=#IMAGE,available=#AVAILABLE,product_category=#CATEGORY,product_brand=#BRAND,product_achv=#ACHIV WHERE id = #ID";
cmd = new SqlCommand(query);
txt_name.Text = "";
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
cmd.Parameters.Add("#ID", id);
param.InsertUpdateData(cmd);
}
else
{
string query = "INSERT INTO Products(product_name,price,unit,product_image,available,product_category,product_brand,product_achv) VALUES(#PRODUCTNAME,#PRIZE,#UNIT,#IMAGE,#AVAILABLE,#CATEGORY,#BRAND,#ACHIV)";
cmd = new SqlCommand(query);
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
param.InsertUpdateData(cmd);
}
}
It is getpicture function used in btn_submit
private void getpicture()
{
try
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string root = Server.MapPath("~");
string path = root + "assets\\images\\products\\";
FileUpload1.SaveAs(path + FileName);
ViewState["pathimage"] = "/assets/images/products/" + FileName;
this.product_image.ImageUrl = "../assets/images/products/upload.png";
}
else
{
Response.Write("Select an Image");
}
}
catch (Exception ex)
{
Response.Write("Select an Image");
}
}
Providing Data access layer Insert Update Data code too
public Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OnlineStoreConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
System.Web.HttpContext.Current.Response.Write("Succed");
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.ToString());
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Server Controls
<div class="row">
<div class="col-md-6">
<asp:TextBox ID="txt_name" runat="server" CssClass="form-control" placeholder="Product Name"></asp:TextBox>
<br />
<asp:TextBox ID="txt_price" runat="server" CssClass="form-control" placeholder="Product Price"></asp:TextBox>
<br />
<asp:TextBox ID="txt_unit" runat="server" CssClass="form-control" placeholder="Product Unit"></asp:TextBox>
<br />
<asp:DropDownList ID="dd_available" runat="server" CssClass="form-control">
<asp:ListItem>Is Product Available</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Not Avaliable</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="dd_category" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_brand" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_achievment" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
</div>
<div class="col-md-2"></div>
<div class="col-md-4">
<asp:Image ID="product_image" runat="server" style="height:231px;width:225px;" CssClass="form-control" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange = "show_image(this);" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3 col-md-offset-6">
<asp:Button ID="btn_Insert" runat="server" Text="Create Product" CssClass="btn btn-primary btn-lg" OnClick="btn_Insert_Click" />
</div>
</div>
Before Clicking update button
Before clicking update button
After I updated text box values respectively and when click button Upload None of my server control value changes. Here it is
Watching local variable
But in case of Creating Product it works
Saad, i think the error is in the page_load event. If in your querystring the update param is not null, then you are always replacing the textboxes with the data of your DB.
Your code should be like this
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Hope it helps...
i am new to dotnet and am just trying out to add a row of text boxes for a grid view DYNAMICALLY.
On load of the page the grid view will be loaded with data as read only.
on clicking edit button, 2nd row will be loaded with text boxes. i succeeded till here. now on entering some data on these text boxes am not able to read the value back in my c# code.
here is my code snippet. can anyone please help me in this.
ASP code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="justGrid._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="170px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="edit" />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="save" />
<br />
</asp:Content>
C# code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
staticTable();
}
bindGrid();
}
protected void staticTable()
{
string[] NamesArray = new string[] { "RAM", "SAM", "TOM", "JERRY" };
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt = ds.Tables.Add();
dt.Columns.Add("Names", typeof(string));
for (int j = 1; j <= 5; j++)
{
dt.Columns.Add("" + j, typeof(string));
}
foreach (string l in NamesArray)
{
dt.Rows.Add(l);
}
dt.Rows[0][1] = "S";
dt.Rows[0][2] = "P";
dt.Rows[0][5] = "P";
dt.Rows[1][2] = "S";
dt.Rows[1][4] = "P";
dt.Rows[2][3] = "S";
dt.Rows[3][1] = "U";
dt.Rows[3][5] = "P";
ViewState["CurrentTable"] = dt;
GridView1.DataSource = ds;
// GridView1.DataBind();
}
protected void bindGrid()
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int k = 1; k <= 5; k++)
{
TextBox tb1 = new TextBox();
tb1.Attributes.Add("runat", "server");
tb1.Width = 15;
tb1.ID = "TBID" + k;
tb1.Text = GridView1.Rows[1].Cells[k].Text.Trim().Replace(" ", string.Empty);
GridView1.Rows[1].Cells[k].Controls.Add(tb1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox box1 = (TextBox)GridView1.Rows[1].Cells[1].FindControl("TBID1");
TextBox1.Text = box1.Text;
}
}
Note: for testing purpose alone..am trying to display the 2nd row 1st column value in textbox.
foreach (GridViewRow row in GridView1.Rows)
{
TextBox box1 = row.FindControl("TBID") as TextBox;
if (box1 != null)
{
string value = box1.Text;
}
}
How can i execute a SELECT query from a drop down list. I have a drop down that contains diploma degrees and in my database i have a table called Alumni(Aid,...,Diploma) and a table called Diploma which contains (Did,Diploma) and we have 5 diplomas manually inserted (brevet,bacc2,bachelor,master,doctoral). What i want is to select a diploma from the drop down list so it can end up in Alumni table after i confirm or submit. Here's my code.
Form.aspx:
<form id="form" runat="server" method="post">
<div>
<table class="style1">
<tr>
<td>Diploma:</td>
<td>
<asp:DropDownList ID="Diploma" runat="server" AppendDataBoundItems="true" Width="160px">
<asp:ListItem Text="Select Degree" Value="Select Degree"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<center>
<asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" Width="85px" />
</center>
</form>
Form.aspx.cs:
protected void Button_Click(object sender, EventArgs e)
{
Session["diploma"] = Diploma.SelectedValue;
if (Status.Text == "1")
{
Response.Redirect("C2.aspx");
}
else
{
Response.Redirect("C1.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["diploma"] != null &&)
{
Diploma.SelectedValue = Session["diploma"].ToString();
}
}
}
C1.aspx.cs:
if (!Page.IsPostBack)
{
if (Session["pname"] != null && Session["plastname"] != null && Session["pos"] != null &&
Session["children"] != null && Session["schoolofchildren"] != null &&
Session["schoolofchildren1"] != null && Session["schoolofchildren2"] != null)
{
PName.Text = Session["pname"].ToString();
PLastName.Text = Session["plastname"].ToString();
OldStudent.Text = Session["pos"].ToString();
Children.Text = Session["children"].ToString();
SchoolOfChildren.Text = Session["schoolofchildren"].ToString();
SchoolOfChildren1.Text = Session["schoolofchildren1"].ToString();
SchoolOfChildren2.Text = Session["schoolofchildren2"].ToString();
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["pname"] = PName.Text;
Session["plastname"] = PLastName.Text;
Session["pos"] = OldStudent.Text;
Session["children"] = Children.Text;
Session["schoolofchildren"] = SchoolOfChildren.Text;
Session["schoolofchildren1"] = SchoolOfChildren1.Text;
Session["schoolofchildren2"] = SchoolOfChildren2.Text;
Response.Redirect("Form.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["pname"] = PName.Text;
Session["plastname"] = PLastName.Text;
Session["pos"] = OldStudent.Text;
Session["children"] = Children.Text;
Session["schoolofchildren"] = SchoolOfChildren.Text;
Session["schoolofchildren1"] = SchoolOfChildren1.Text;
Session["schoolofchildren2"] = SchoolOfChildren2.Text;
Response.Redirect("C2.aspx");
}
protected void Button4_Click(object sender, EventArgs e)
{
try
{
ExecuteInsert1(Session["diploma"].ToString());
ExecuteInsert2(PName.Text, PLastName.Text, OldStudent.SelectedValue, Children.SelectedValue, SchoolOfChildren.Text, SchoolOfChildren1.Text,
SchoolOfChildren2.Text);
Response.Write("Successfully Added!");
ClearControls(Page);
Session.Clear();
}
catch{}
}
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["Champville1ConnectionString"].ConnectionString;
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls) ClearControls(c);
}
}
private void ExecuteInsert1(string diploma)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Alumni (Diploma) VALUES " + " (#Diploma)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("#Diploma", SqlDbType.NVarChar, 50);
param[0].Value = diploma;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private void ExecuteInsert2(...){}
It shows no error until and unless i add a record, it goes into catching exception which gives me connection problem as output. I tried alot but couldn't find my mistake.This is my code:
public partial class Default2 : System.Web.UI.Page
{
private string conStr = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
FillList();
BtnsActive(false, true, false, false, false, false);
}
}
protected void BtnsActive(bool a, bool b, bool c, bool d, bool e, bool f)
{
Panel2.Enabled = a;
btnAdd.Enabled = b;
btnInsert.Enabled = c;
btnEdit.Enabled = d;
btnUpdate.Enabled = e;
btnDelete.Enabled = f;
}
protected void FillList()
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Select * from Student order by StudId", con);
SqlDataReader reader;
DropDownList1.Items.Clear();
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["StudId"] + "," + reader["StudFirstName"];
newItem.Value = reader["StudId"].ToString();
DropDownList1.Items.Add(newItem);
}
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Select * from Student where StudId='" + DropDownList1.SelectedValue + "'", con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
TextBox1.Text = reader["StudId"].ToString();
TextBox2.Text = reader["StudFirstName"].ToString();
CheckBox1.Checked = (bool)reader["Library"];
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, true, false, true);
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
BtnsActive(true, false, true, false, false, false);
TextBox1.Text = "";
TextBox2.Text = "";
CheckBox1.Checked = false;
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Insert into Student (StudId,StudFirstName,Library) values(#sid,#name,#library)", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.Parameters.AddWithValue("#library", CheckBox1.Checked);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Record has been added.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
BtnsActive(true, false, false, false, true, false);
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Update Student set StudId=#id,StudFirstName=#name,Library=#library) where StudId=#oldId", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.Parameters.AddWithValue("#library", CheckBox1.Checked);
cmd.Parameters.AddWithValue("#oldId", DropDownList1.SelectedValue);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('The Record has been Updated.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Delete from Student where StudId=#id", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('The Record has been Deleted.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
}
and this is my design code which is simple..
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" BackColor="#CC3300">
Stud ID:<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />
<asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="Insert" />
<asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" />
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" BackColor="#FF9933">
<br />
<br />
Stud ID:
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<br />
Name:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
Library :
<asp:CheckBox ID="CheckBox1" runat="server" />
</asp:Panel>
</div>
</form>
</body>
</html>