selection through drop down list - c#

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(...){}

Related

Move selected items from one listbox to another in C#

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:

Datasource to asp calendar

I'm trying to bind mysql data to asp:calendar but its not working. I need to display the data in mysql table slotavailable column according to the date column. How can I get it into the calendar cells?
<asp:Calendar ID="cal2" runat="server" Width="50%" DayField="Date" OnDayRender="Calendar1_DayRender"
BackColor="Orange" NextMonthText="Next" PrevMonthText="Prev" >
<DayStyle CssClass="days" VerticalAlign="Top" Font-Name="Arial" Height="80px" BackColor="lightYellow" />
<TodayDayStyle BackColor="Orange" />
<OtherMonthDayStyle BackColor="LightGray" ForeColor="DarkGray"/>
</asp:Calendar>
Below would be the cs code to fetch data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cal2.VisibleDate = DateTime.Today;
FillLeaveplannerDataset();
}
}
protected void FillLeaveplannerDataset()
{
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM dummy WHERE date >= #firstDate AND date < #lastDate", con);
cmd.Parameters.Add(new MySqlParameter("#firstDate", firstDate));
cmd.Parameters.Add(new MySqlParameter("#lastDate", lastDate));
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
}
catch { }
return dsMonth;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var slot = dr["slotavailable"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillLeaveplannerDataset();
}
How can get the slot column data into the calendar cell?
You please make sure that your nextDate and e.Day.Date are matches and then change in your code like
e.Cell.Controls can add any text to your cell
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var slot = dr["slotavailable"];
if (nextDate == e.Day.Date)
{
//This is the line where we add slotavailable column data
e.Cell.Controls.Add(new LiteralControl($"<p>{slot}</p>"));
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
The output will be
The advantage of e.Cell.Controls you may add html button or span or image or any else as your need
And e.Cell.Controls.Clear(); may help you to clear all controls related to particular cell
Try once may it help you

Textbox value doesn't change on button click event in asp.net C#

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...

Dropdownlist does not update after adding update panel

I have multiple dropdownlist box all querying the same column, same table and from the same database. For example under memberID column i have the following IDs.
12345
23456
34567
And i have 3 different dropdownlist box as shown below
<asp:DropDownList ID="memberID3" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="memberID1" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
I added update panel between the dropdownlist so as to allow my dropdownlist to refresh upon any updates/selections.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
For instance, when memberID1 selected 12345, the other 2 dropdownlist (memberID2 and 3) will not display the ID 12345. Vice versa, when memberID1 select the default value of the dropdownlist, the ID reappears in the other 2 dropdownlistbox. I have added a default value for all of the DDL.
memeberID(number).Items.Insert(0, new ListItem(" Please select a Member ID", ""));
memeberID(number).SelectedIndex = 0;
If i have not mistaken the property of update panel, isn't that able to make this function work?
here is the binding code as requested.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
memberID1.Items.Clear();
memberID1.DataSource = ds2;
memberID1.DataTextField = "memberID";
memberID1.DataValueField = "memberID";
memberID1.DataBind();
memberID1.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID1.SelectedIndex = 0;
memberID2.Items.Clear();
memberID2.DataSource = ds2;
memberID2.DataTextField = "memberID";
memberID2.DataValueField = "memberID";
memberID2.DataBind();
memberID2.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID2.SelectedIndex = 0;
memberID3.Items.Clear();
memberID3.DataSource = ds2;
memberID3.DataTextField = "memberID";
memberID3.DataValueField = "memberID";
memberID3.DataBind();
memberID3.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID3.SelectedIndex = 0;
}
UPDATE
For now i'm able to allow my other ddl to re-bind and cache the selected value in the other dropdownlist when the default value is selected. However, when i select other ID, the ID are being removed and it wont re-bind the other ddl.
protected void FillddlLocations()
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.Visible = false;
ddlpid2.Visible = false;
ddlpid3.Visible = false;
ddlpid4.Visible = false;
ddlpid5.Visible = false;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Police ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid1.SelectedIndex > 0)
{
Session["pid1"] = ddlpid1.SelectedValue;
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else
if (ddlpid1.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid2.SelectedIndex > 0)
{
Session["pid2"] = ddlpid2.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid2.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid3.SelectedIndex > 0)
{
Session["pid3"] = ddlpid3.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid3.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid4_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid4.SelectedIndex > 0)
{
Session["pid4"] = ddlpid4.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid4.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid5_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid5.SelectedIndex > 0)
{
Session["pid5"] = ddlpid5.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
}
else if (ddlpid5.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
}
}
First of all, I would set the AutoPostBack property for dropdowns to true in my markup:
<asp:DropDownList ID="memberID1" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID3" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
Update: We can store selected values in view state and retrieve after repopulating the dropdownlists like below:
public partial class WebForm2 : System.Web.UI.Page
{
bool bFlag = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillddlLocations();
}
}
//Properties to store selected value in ViewState
protected string MemberID1Selection
{
get
{
if (ViewState["MemberID1Selection"] != null)
return ViewState["MemberID1Selection"].ToString();
return "";
}
set { ViewState["MemberID1Selection"] = value; }
}
protected string MemberID2Selection
{
get
{
if (ViewState["MemberID2Selection"] != null)
return ViewState["MemberID2Selection"].ToString();
return "";
}
set { ViewState["MemberID2Selection"] = value; }
}
protected string MemberID3Selection
{
get
{
if (ViewState["MemberID3Selection"] != null)
return ViewState["MemberID3Selection"].ToString();
return "";
}
set { ViewState["MemberID3Selection"] = value; }
}
protected void FillddlLocations()
{
FillDropdown(memberID1);
FillDropdown(memberID2);
FillDropdown(memberID3);
memberID1.Visible = true;
memberID2.Visible = true;
memberID3.Visible = true;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataTextField = "memberID";
ddl.DataValueField = "memberID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select a Member ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void IndexChanged(DropDownList ddlChanged, DropDownList ddlToFilter1, DropDownList ddlToFilter2)
{
string removeValue1 = ddlChanged == memberID1 ? MemberID1Selection : (ddlChanged == memberID2 ? MemberID2Selection : MemberID3Selection);
string selValue2 = ddlChanged == memberID1 ? MemberID2Selection : (ddlChanged == memberID2 ? MemberID1Selection : MemberID1Selection);
string selValue3 = ddlChanged == memberID1 ? MemberID3Selection : (ddlChanged == memberID2 ? MemberID3Selection : MemberID2Selection);
bFlag = false;//Prevent fireing the code again while changing the index
if (removeValue1 != "")
{
ListItem item1 = ddlToFilter1.Items.FindByValue(removeValue1);
ddlToFilter1.Items.Remove(item1);
ListItem item2 = ddlToFilter2.Items.FindByValue(removeValue1);
ddlToFilter2.Items.Remove(item2);
}
if (selValue3 != "")
{
ListItem item3 = ddlToFilter1.Items.FindByValue(selValue3);
ddlToFilter1.Items.Remove(item3);
}
if (selValue2 != "")
{
ListItem item4 = ddlToFilter2.Items.FindByValue(selValue2);
ddlToFilter2.Items.Remove(item4);
}
bFlag = false;
ddlToFilter1.SelectedIndex = ddlToFilter1.Items.IndexOf(ddlToFilter1.Items.FindByValue(selValue2));
ddlToFilter2.SelectedIndex = ddlToFilter2.Items.IndexOf(ddlToFilter2.Items.FindByValue(selValue3));
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID1Selection = memberID1.SelectedValue;
if (bFlag)
{
FillDropdown(memberID2);
FillDropdown(memberID3);
IndexChanged(memberID1, memberID2, memberID3);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID2Selection = memberID2.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID3);
IndexChanged(memberID2, memberID1, memberID3);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID3Selection = memberID3.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID2);
IndexChanged(memberID3, memberID1, memberID2);
}
}
}
I have tested the code and it is working for me. Hope it helps!

Radio button list selected value not persistent in asp.net

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

Categories