Binding the 2 EVALS on one LinkButton - c#

I am looking a way to allow my two EVALS in my CS. The 1st string works perfectly, but the other one does not
This is my aspx
<asp:ListView ID="lvMaterialsList" runat="server" ondatabound="lvMaterialsList_DataBound"
onpagepropertieschanging="lvMaterialsList_PagePropertiesChanging" OnItemCommand="lvMaterialsList_ItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("SupplierProduct")%> ' Visible="false" /></td>
<td>
<td>
<asp:Label ID="ltRefNo" runat="server" Text='<%# Eval("ReqMatID") %>' Visible="false" />
<%# Eval("SupplierProduct")%>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("SupplierProductID") %>' width="1px" Visible="false" />
</td>
<td><%# Eval("Quantity") %></td>
<td><asp:TextBox ID="txtAlloted" runat="server" type="number" Text=''
class="form-control" width="60px" min='1'/></td>
<td><asp:LinkButton ID="btnUpdate" runat="server" OnClientClick='return confirm("Withdraw materials?")' CommandName="updateused">
<i class="fa fa-refresh"></i> </asp:LinkButton>
</td>
<td><asp:Literal ID="ltUsed" runat="server" Text='<%# Eval("Used") %>'
Visible="false" />
<%# Eval("Used")%>
</td>
<td><%# Eval("Status") %></td>
<td><%# Eval("DateAdded", "{0: MMMM dd, yyyy}") %></td>
<td><%# Eval("DateModified", "{0: MMMM dd, yyyy}") %></td>
<td>
<td>
<asp:LinkButton Text="Additional" class="btn btn-primary " ID="lbtnUpdate" runat="server" CommandArgument='<%#Eval("ProjectID")+","+ Eval("ReqMatID")%>'
PostBackUrl='<%# string.Format(" AdditionalAlloc.aspx?ID={0}&MID={1}", Eval("ProjectID"), Eval("ReqMatID"))%>'></asp:LinkButton>
<asp:LinkButton Text="Add req" class="btn btn-primary " ID="lblAdd" runat="server"
PostBackUrl='<%# string.Format(" AddReq.aspx?ID={0}", Eval("ProjectID"))%>'></asp:LinkButton>
</i>
<%-- </i> --%>
<a href='DeleteMaterial.aspx?ID=<%# Eval("ReqMatID") %>'" onclick='return confirm("Delete record?")'>
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<tr>
<td colspan="12"><h2 class="text-center">No records found.</h2></td>
</td>
</tr>
</EmptyDataTemplate>
</asp:ListView>
This is the code that I use.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Admin_Project_AdditionalAlloc : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetCon());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ID"] != null)
{
int userID = 0;
bool validUser = int.TryParse(Request.QueryString["ID"].ToString(), out userID);
int productID = 0;
bool product = int.TryParse(Request.QueryString["MID"].ToString(), out productID);
if (validUser)
{
if (!IsPostBack)
{
GetInfo(userID);
GetMaterialsInfo(productID);
GetProjects();
GetMaterials();
}
}
else
Response.Redirect("Default.aspx");
}
else
Response.Redirect("Default.aspx");
ddlProjectName.Enabled = false;
ddlProjectName.CssClass = "form-control";
ddlMaterials.Enabled = false;
ddlMaterials.CssClass = "form-control";
Panel1.Visible = false;
}
void GetProjects()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProjectID, ProjectName FROM Project";
SqlDataReader dr = cmd.ExecuteReader();
ddlProjectName.DataSource = dr;
ddlProjectName.DataTextField = "ProjectName";
ddlProjectName.DataValueField = "ProjectID";
ddlProjectName.DataBind();
con.Close();
ddlProjectName.Items.Insert(0, new ListItem("Select Project", ""));
}
void GetInfo(int ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT ProjectID FROM Project WHERE ProjectID=#ProjectID";
cmd.Parameters.AddWithValue("#ProjectID", ID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ddlProjectName.SelectedValue = dr["ProjectID"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
void GetMaterialsInfo(int MID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT project.ProjectID, RequiredMaterials.ReqMatID FROM Project Inner join RequiredMaterials on RequiredMaterials.ProjectID = Project.ProjectID WHERE Project.ProjectID=#ProjectID AND RequiredMaterials.ReqMatID=#ReqMatID";
cmd.Parameters.AddWithValue("#ProjectID", ID);
cmd.Parameters.AddWithValue("#ReqMatID", MID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ddlMaterials.SelectedValue = dr["ReqMatID"].ToString();
}
con.Close();
}
else
{
con.Close();
//Response.Redirect("Default.aspx");
}
}
void GetMaterials()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT project.ProjectID, ProjectName, RequiredMaterials.ReqMatID, Products.ProductName + ' (' + SupplierName +')' as SupplierProduct FROM Project Inner join RequiredMaterials on RequiredMaterials.ProjectID = Project.ProjectID INNER JOIN SupplierProducts ON RequiredMaterials.ProductID = SupplierProducts.ProductID INNER JOIN Products ON SupplierProducts.ProductID = Products.ProductID INNER JOIN Supplier ON SupplierProducts.SupplierID = Supplier.SupplierID WHERE Project.ProjectID=#ProjectID AND RequiredMaterials.ReqMatID=#ReqMatID ";
cmd.Parameters.AddWithValue("#ProjectID", ID);
cmd.Parameters.AddWithValue("#ReqMatID", ID);
SqlDataReader dr = cmd.ExecuteReader();
ddlMaterials.DataSource = dr;
ddlMaterials.DataTextField = "SupplierProduct";
ddlMaterials.DataValueField = "ReqMatID";
ddlMaterials.DataBind();
con.Close();
ddlMaterials.Items.Insert(0, new ListItem("Select Project", ""));
}
}
This is how I am using my listview
protected void lvMaterialsList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label ltRefNo = (Label)e.Item.FindControl("ltRefNo");
Label label1 = (Label)e.Item.FindControl("Label1");
Label label2 = (Label)e.Item.FindControl("Label2");
TextBox txtAlloted = (TextBox)e.Item.FindControl("txtAlloted");
Literal ltUsed = (Literal)e.Item.FindControl("ltUsed");
bool existingSupply = IsExisting();
bool hasquantity = HasInventory(label1.Text);
int alloted = Convert.ToInt32(txtAlloted.Text);
int productid = Convert.ToInt32(label1.Text);
string Label2 = label2.Text;
var inventory = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM Inventory", con))
{
da.Fill(inventory);
}
var products = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM SupplierProducts", con))
{
da.Fill(products);
}
if (e.CommandName == "updateused")
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (alloted < 0)
{
quantityCheck.Text = "cannot input negative number as quantity";
Panel1.Visible = true;
return;
}
int finalQuantity = Convert.ToInt32(inventory.Rows[0]["Quantity"]) - alloted;
int criticalLevel = Convert.ToInt32(products.Rows[0]["CriticalLevel"]);
bool isSafe = finalQuantity >= criticalLevel;
string status = String.Empty;
if (finalQuantity <= criticalLevel && finalQuantity != 0)
{
status = "Critical";
}
else if (finalQuantity > criticalLevel)
{
status = "Available";
}
else
{
status = "Unavailable";
}
if (existingSupply && hasquantity && isSafe)
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=Used + #Used, DateModified=#DateModified WHERE ReqMatID=#ReqMatID";
cmd.Parameters.AddWithValue("#Used", alloted);
cmd.Parameters.AddWithValue("#ReqMatID", ltRefNo.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Inventory SET Quantity = Quantity - #Quantity, Status=#Status " +
"WHERE ProductID=#ProductID";
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.Parameters.AddWithValue("#Status", status);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Withdraw VALUES (#ProjectID, #ProductID, #SupplierID, #Quantity,#UserID, #DateWithdrawn)";
cmd.Parameters.AddWithValue("#ProjectID", ddlProjects.SelectedValue);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.Parameters.AddWithValue("#SupplierID", DBNull.Value );
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#UserID", Session["userid"].ToString());
cmd.Parameters.AddWithValue("#DateWithdrawn", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
GetMaterialsList();
}
else if (!isSafe)
{
quantityCheck.Text = Label2 + #" Inventory count will be lower than the critical level.";
Panel1.Visible = true;
}
else
{
Panel1.Visible = true;
quantityCheck.Text = Label2 + " Cannot input inventory";
}
}
}
I keep on getting an error:
Object reference not set to an instance of an object.
I have debug the system and it show:
Conversion failed when converting the nvarchar value '__Page' to data type int.

Since you have your LinkButton on the form itself and not inside any databound control your current code will not work because Eval method can be only used with databound controls. Now, I am really not sure how you are able to get ProjectID working. You should always try to avoid complicating the mark-up code. If you have everything in your code behind file why complicate things? Simply do it in your code behind file.
MarkUp (aspx page):-
<asp:LinkButton ID="lbtnUpdate" Text="Additional" class="btn btn-primary"
runat="server"></asp:LinkButton>
In Code Behind:-
lbtnUpdate.PostBackUrl = String.Format("AdditionalAlloc.aspx?ID={0}&MID={1}",
ProjectID,ReqMatID);

Related

Trying to store List View ID

i'm trying to store the id number of records from the list view table thru check box and other values, and I got this error after i hit the submit button. It says there is a null.
Here is the populate the table:
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM
Employees ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
Here is the submit click code:
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmpPart");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", 1);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
//con.Close();
}
}
}
}
}
}
Here is the .aspx
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td>
<asp:CheckBox ID="cbEmployee" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Start by adding the DataKeyNames to the ListView on the aspx page.
<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">

Selected check box in the list view item template is not storing

I'm trying to store the selected rows using asp:checkbox to the CourseParticipants table but it doesn't store the selected records to the database. There is no error shown but it refresh to the same page and shows the checked records. I'm trying to select users.
Thank you in advance!
Here is the markup:
<table class="table table-hover">
<thead style="background-color: #92d36e">
<tr>
<td><b>Employee Name</b></td>
<td><b>Position</b></td>
<td><b>Actions</b></td>
</tr>
</thead>
<tbody>
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td><asp:CheckBox ID="cbEmployee" runat="server" />
</a></td>
</tr>
</ItemTemplate>
</asp:ListView>
</tbody>
</table>
<asp:Button ID="btnAddParticipants" runat="server"
class="btn btn-success" OnClick="btnAddParticipants_Click"
Text="Add Participants" />
Here is the C#
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM Employees";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmployee");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
If it's always DateTime.Now what you want to insert, you could use the getdate() function:
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, getdate())";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.ExecuteNonQuery();
}
But it's a bit DB specific, so what DB are you using?
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql?view=sql-server-2017
I would also cast/convert txtCourseID.Text to an int (32 or 64) depending on your db scheme. Just to make sure that it's an OK value... and not string (nvarchar).
I also removed the closing of the connection, since it's in a using block.

Dropdownlist not showing correct selected value in ASP.NET Repeater Web application

I have a few ASP.NET Repeaters that have drop down lists in them and they all need to be populated with the correct information and then display the selected value for each data row it is displaying. In one repeater (CompanyRepeater), the correct selected value is chosen. In another repeater (SoldRepeater), the correct selected value is NOT chosen. So the drop down list in CompanyRepeater does work but the one in SoldRepeater does not work. The code is the same for both repeaters and I cannot figure out why the second one is not working. Both drop down lists populate with the correct information but the second repeater does not display the correct selected value. Please help me figure out why the correct selected value is not being selected. Below is my code. Please let me know if there is anymore information needed to help me. Any help is much appreciated. First is my front end code.
<asp:Repeater ID="CompanyRepeater" runat="server" OnItemDataBound="CompanyRepeater_ItemDataBound" OnItemCommand="CompanyRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Company</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("Date") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>OldName
<br />
<asp:TextBox ID="txtOldNameChange" Text='<%#Eval("OldName") %>' runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<br /> State:
<asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
</td>
<td>New Name
<br />
<asp:TextBox ID="txtNewNameChange" runat="server" Text='<%#Eval("NewName") %>'></asp:TextBox>
</td>
<td rowspan="3" style="width: 50px; float: right;">
<asp:Button ID="btnUpdateName" runat="server" Text="Update" CommandName="Update" />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
<hr />
<asp:Repeater ID="SoldRepeater" runat="server" OnItemDataBound="SoldRepeater_ItemDataBound" OnItemCommand="SoldRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Sold Event</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtSoldDate" runat="server" Text='<%#Eval("EventDate") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtSoldNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>Sold to Company
<br />
<asp:TextBox ID="txtSoldTo" Text='<%#Eval("SoldToCompany") %>' runat="server"></asp:TextBox>
<br /> Sold to Type
<asp:DropDownList ID="ddlSoldTo" runat="server"></asp:DropDownList>
</td>
<td rowspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%#Eval("CompID") %>' />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
This is my backend code
protected void Page_Load(object sender, EventArgs e)
{
_cID = Convert.ToInt32(Request.QueryString["CompID"]);
if (!Page.IsPostBack)
{
PopulateCompanyRepeater();
PopulateSoldEvent();
}
}
private void PopulateCompanyRepeater()
{
DALAccessData a = new DALAccessData(connString);
_listInfo = a.GetCompInfo(_cID);
CompanyRepeater.DataSource = _listInfo;
CompanyRepeater.DataBind();
}
private void PopulateSoldEvent()
{
DALSectionAccessData a = new DALSectionAccessData(connString);
_listEvents = a.GetSoldEvents(_cID);
SoldRepeater.DataSource = _listEvents;
SoldRepeater.DataBind();
}
protected void CompanyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)e.Item.FindControl("ddlState");
Corp co = (Corp)e.Item.DataItem;
Corp st = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT a.Country_ID, a.CountryName FROM States c INNER JOIN Countries a ON a.Country_ID = c.Country_ID";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "CountryName";
ddl.DataValueField = "Country_ID";
ddl.DataBind();
cn.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (co.Country_ID == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
}
else
{
ddl.Items[i].Selected = false;
}
}
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl2.DataSource = ds.Tables[0];
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "StateID";
ddl2.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl2.Items.Count; i++)
{
if (!String.IsNullOrEmpty(ddl2.Items[i].Value))
{
if (st.StateID == Convert.ToInt32(ddl2.Items[i].Value))
{
ddl2.Items[i].Selected = true;
}
else
{
ddl2.Items[i].Selected = false;
}
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlState");
ddl2.Items.Clear();
using(SqlConnection conn = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cmd.Connection = conn;
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem _listStates = new ListItem();
_listStates.Text = sdr["StateName"].ToString();
_listStates.Value = sdr["StateID"].ToString();
ddl2.Items.Add(_listStates);
}
}
}
}
ddl2.AppendDataBoundItems = true;
ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
ddl2.SelectedIndex = -1;
}
protected void SoldRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlSoldTo");
int x = ((CorpEvents)e.Item.DataItem).SoldToTypeID;
//Corp x = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT SoldToTypeID, SoldToTypeName FROM SoldToType";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "SoldToTypeName";
ddl.DataValueField = "SoldToTypeID";
ddl.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
}
}
My data access layer code
public List <Corp> GetCompInfo(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, CONVERT(varchar(10), a.Date, 120) AS Date, a.Notes, b.StateID, b.OldName, b.NewName, c.Country_ID FROM NameChange b INNER JOIN CompanyInfo a ON a.CompID = b.CompID INNER JOIN States c ON c.StateID = b.StateID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.NewName = row["NewName"].ToString();
e.OldName = row["OldName"].ToString();
e.StateID = Convert.ToInt32(row["StateID"].ToString());
e.Notes = row["Notes"].ToString();
e.CountryID = Convert.ToInt32(row["Country_ID"].ToString());
e.Date = Convert.ToDateTime(row["Date"].ToString());
e.Date.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
public List <Corp> GetSoldEvents(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, a.Notes, a.Date, b.SoldToCompany, c.SoldToTypeName, c.SoldToTypeID FROM CompanyInfo a INNER JOIN SoldEvent b ON a.CompID = b.CompID INNER JOIN SoldToType c ON b.SoldToTypeID = c.SoldToTypeID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.SoldToCompany = row["SoldToCompany"].ToString();
e.SoldToTypeName = row["SoldToTypeName"].ToString();
e.SoldToTypeID = Convert.ToInt32(row["SoldToTypeID"].ToString());
e.Notes = row["Notes"].ToString();
e.EventDate = Convert.ToDateTime(row["Date"].ToString());
e.EventDate.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
IMHO, your method of setting the selected value is rather cumbersome. This entire section of code:
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
Can be replaced with a single line:
ddl.SelectedValue = x.ToString();
In addition, once you do find the matching value you continue to loop on the items, rather than exiting out of the loop.
Try these changes, they may solve the problem for you.
A few other items that I noticed:
The code to retrieve the SoldToType is called for each item in the
repeater. I would suggest retrieving this data once and referencing
it for each item, rather than going to the db each time.
Your SQL code is wide open to SQL injection. Use parameterized queries, like so:
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = #CountryID";
...
cmd.Parameters.AddWithValue("CountryID", ddl.SelectedValue);

How to insert text and value from checkbox in datalist into sql server

i have datalist filled by checkbox. the code like this
the form
<asp:DataList ID="DataListTest" runat="server" OnPreRender="PreTes">
<ItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td><asp:Label ID="lblsubheader" runat="server" /></td>
</tr>
<tr>
<td>
<asp:HiddenField ID="subhd" runat="server" Value='<%# Eval("sub_category") %>' />
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="cbNameAccess" runat="server" Text='<%# Eval("name_access") %>' />
<asp:HiddenField ID="hd" runat="server" Value='<%# Eval("name_category") %>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
the code to get data from database
private void ShowDataList()
{
conn.Open();
string sql = "Select access.id_access, access.nama_access, jenis_access.id_jenis_access ,jenis_access.nama_jenis_access as 'nama_jenis', sub_jenis.nama_sub_jenis as 'sub_jenis',sub_jenis.id_sub_jenis "+
"FROM access LEFT JOIN detil_access ON access.id_access = detil_access.id_access "+
"LEFT JOIN jenis_access ON detil_access.id_jenis_access = jenis_access.id_jenis_access "+
"LEFT JOIN sub_jenis ON detil_access.id_sub_jenis = sub_jenis.id_sub_jenis "+
"ORDER BY jenis_access.id_jenis_access";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
dt = new DataTable();
adp.Fill(dt);
DataListTest.DataSource = dt;
DataListTest.DataBind();
}
the code to show data from database into datalist and show it as Checkbox
protected void PreTes(object sender, EventArgs e)
{
string temp = "";
string subtemp ="";
foreach (DataList item in DataListTest.Items)
{
Label objLabel = item.FindControl("lblHeader") as Label;
Label subjenis = item.FindControl("lblsubheader") as Label;
CheckBox objName = item.FindControl("cbCountryName") as CheckBox;
HiddenField objHD = item.FindControl("hd") as HiddenField;
HiddenField subobjHD = item.FindControl("subhd") as HiddenField;
if (temp != objHD.Value)
{
temp = objHD.Value;
objLabel.Text = temp + "<br/>";
}
if (subtemp != subobjHD.Value)
{
subtemp = subobjHD.Value;
subjenis.Text = subtemp+"<br/>";
}
}
}
the code for insert into sql
private void InsertActivationDetail()
{
// get idActivation
int MaxActivationId = GetGenerateActivationID();
//
foreach (DataList objitem in DataListTest.Items)
{
if (objitem.Selected)
{
conn.Open();
sql = "INSERT INTO detil_activation (id_activation_access, id_jenis_access, id_access, " +
"others_all, others_nama_access, call_back_to, reason_any_number, description_other_jenis_access, " +
"reason_others_jenis_access) VALUES ('" +
MaxActivationId + "', (select id_jenis_access from access where id_access = '" +
objitem.Value + "'), '" + objitem.Value + "',NULL,NULL,NULL,NULL,NULL,NULL)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
my question is "How to insert id and name(text and value) from checkbox into database sql server"
i think the problem is around function InsertActivationDetail(). because i have red underline on it. Would you mind to help me please ?
FYI = i'm a newbie in here also programmer.
Try this. Modified your Method a little. Your are not getting the CheckBox within your DataList.
private void InsertActivationDetail()
{
// get idActivation
int MaxActivationId = GetGenerateActivationID();
//
foreach (DataListItem objitem in DataListTest.Items)
{
CheckBox cbNameAccess = (CheckBox)objitem.FindControl("cbNameAccess");
if (cbNameAccess != null)
{
if (cbNameAccess.Checked==true)
{
conn.Open();
sql = "INSERT INTO detil_activation (id_activation_access, id_jenis_access, id_access, " +
"others_all, others_nama_access, call_back_to, reason_any_number, description_other_jenis_access, " +
"reason_others_jenis_access) VALUES ('" +
MaxActivationId + "', (select id_jenis_access from access where id_access = '" +
cbNameAccess.Text + "'), '" + cbNameAccess.Text + "',NULL,NULL,NULL,NULL,NULL,NULL)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}

Dropdown value disappears after submit

I have a textbox whose values goes into the dropdown on button click. The problem is that when I fill all the data and submit the form. And when I come second time to see that value it disappears from the dropdown. What should I do to make the value gets in the dropdown fix. Please see the code for your reference:
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
Also, see the code behind for your reference:-
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLocation.SelectedItem.Text == "Other")
{
txtOtherCity.Visible = true;
}
else
{
txtOtherCity.Visible = false;
}
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string city = txtOtherCity.Text.Trim();
if (!string.IsNullOrEmpty(city))
{
ddlLocation.Items.Add(new ListItem(city, city));
}
}
You have to store the values from the textbox into the table dbo.Cities in database. Next time when you will come back to the same page then dropdown will fetch data from db.
Then on btnAddDropDown_Click1() you should insert the value of the city from the 'txtOtherCity' TextBox to the respective table, and then bind the DropDown of the city again. Something Like
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string strconnection = System.Configuration.ConfigurationManager.AppSettings["YourConnectionString"].ToString();
string city = txtOtherCity.Text.Trim();
DataSet ds=new DataSet();
if (!string.IsNullOrEmpty(city))
{
// Your code to insert the value of the city from the 'txtOtherCity' `TextBox` to the respective table
//Edit: this is a very rudimentary code
string query = "INSERT INTO Career.Location (State) " +
"VALUES (#city) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(strconnection))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#city", SqlDbType.VarChar, 50).Value = city;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
query = "select State from Career.Location";
using(SqlConnection cnn = new SqlConnection(strconnection))
using(SqlCommand cmdd = new SqlCommand(query, cnn))
{
SqlDataAdapter adp = new SqlDataAdapter(cmdd);
cnn.Open();
adp .Fill(ds);
cnn.Close();
}
ddlLocation.DataSource=ds;
ddlLocation.DataTextField = "State";
ddlLocation.DataValueField = "State";
ddlLocation.DataBind();
}
}
Do you have functionality of inserting the data in the DB (not only adding the new item in the drop down list). You have to insert the city in the appropriate table to be able to see it later on.
The implementation depends on your architecture, the implementation of the DAL etc.
For example - if you are using ADO.NET, you can insert the values in the table with a stored procedure:
CREATE PROCEDURE Add_City
#CityName varchar(50),
#StateID int
AS
BEGIN
INSERT INTO dbo.Cities (CityName, StateID) values (#CityName, #StateID)
END
GO
And then call it from the app. Something like that:
using (SqlConnection con = new SqlConnection("the connection string"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_City";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("#StateID", SqlDbType.Int).Value = CountryId;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
throw ex; // Or log or handle somehow the exception
}
}
I got the answer for this solution, Please see the code for your reference:-
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
protected void ddllocation1_SelectedIndexChanged(object sender, EventArgs e)
{
string country = "India";
var cities = _helper.GetLocations(country, ddllocation1.SelectedValue);
cities.Insert(0, "--Select--");
cities.Insert(1, "Other");
ddlLocation.DataSource = cities;
ddlLocation.DataBind();
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//BindContrydropdown();
//if (txtOtherCity.Text != "")
//{
// txtOtherCity.Text = "";
//}
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddlLocation.SelectedItem.ToString();
cmd.Connection = con;
try
{
// con.Open();
cmd.ExecuteNonQuery();
BindContrydropdown();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
Also see the html of the dropdowns:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
And this solved my,
Also see the Stored procedure for the same:-
Alter PROCEDURE [dbo].[Add_CityforLocation]
-- Add the parameters for the stored procedure here
#ID int,
#CountryName nvarchar(100),
#StateName nvarchar(100),
#CityName varchar(100)
AS
BEGIN
INSERT INTO Career.Location(CountryName, StateName, CityName) values (#CountryName,#StateName,#CityName)
END
GO

Categories