I'm trying to create a Image Dynamically. I got the Link to the Image.
necessary code:
foreach (String pictureLink in imageLinks)
{
Image image = new Image();
image.ImageUrl = pictureLink;
imagesDiv.Controls.Add(image);
}
But nothing is happens.. How can I do that or what I'm doing wrong?
The Style, of how the pictures should be showed is Googleimagesearch result like..
EDIT:
There is one more thing I would do.. When adding the Placeholders (with the Image), they are showed after all Images where been loaded, but is it possible to add the placeholder with the image, right after it has been added?
take a look at this
Adding asp.net image to div
I think it should answer your questions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Types;
using BOO;
using BOFactory;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace DAL
{
public class CustomerDAL:ICustomerDAL
{
List<ICustomerBO> emplist = new List<ICustomerBO>();
List<ICustomerBO> llist = new List<ICustomerBO>();
public List<ICustomerBO> DBbind()
{
string connectionstring = ";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_databinding";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string locn = reader["location"].ToString();
ICustomerBO loc = new CustomerBO(locn);
llist.Add(loc);
}
connection.Close();
return llist;
}
public int addemployee(ICustomerBO b)
{
string connectionstring = "Server= LENOVO\\SQLEXPRESS, Authentication=Windows Authentication, Database= tempdb";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_addemployee";
command.Connection = connection;
command.Parameters.AddWithValue("#employeename", b.empname);
command.Parameters.AddWithValue("#dob", b.dob);
command.Parameters.AddWithValue("#location", b.location);
command.Parameters.AddWithValue("#gender", b.gender);
command.Parameters.AddWithValue("#doj", b.doj);
command.Parameters.AddWithValue("#experience", b.experience);
command.Parameters.AddWithValue("#CTC", b.ctc);
command.Parameters.AddWithValue("#designation", b.designation);
command.Parameters.AddWithValue("#unithead", b.unithead);
command.Parameters.AddWithValue("#projectid",b.projectid);
command.Parameters.AddWithValue("#id", 0);
command.Parameters["#id"].Direction = ParameterDirection.Output;
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if(rowaffected>0)
{
return rowaffected;
}
else
{
return 0;
}
}
public bool LOGIN(ICustomerBO l)
{
bool flag = false;
string connectionstring = "Data Source=sql1;" + ";" + "user id=;"
+ "password=tcstvm;";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_loginview";
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string name = reader["UserName"].ToString();
string pwd = reader["Password"].ToString();
if((name==l.name)&&(pwd==l.pwd))
{
flag = true;
}
}
connection.Close();
return flag;
}
public List<ICustomerBO> viewallListBO()
{
string ConnectionString = "";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_viewemp7";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["employeename"].ToString();
DateTime dob = Convert.ToDateTime(reader["dob"]);
string locn = reader["location"].ToString();
string gender = reader["gender"].ToString();
DateTime doj = Convert.ToDateTime(reader["doj"]);
int exp = Convert.ToInt32(reader["experience"]);
int ctc = Convert.ToInt32(reader["ctc"]);
string desg = reader["designation"].ToString();
string head = reader["unithead"].ToString();
int proj =Convert.ToInt32( reader["projectid"]);
ICustomerBO employee=BOFactory.CustomerBOFactory.ADDEMPLOYEE(id, name, dob, locn, gender, doj, exp, ctc, desg, head, proj);
emplist.Add(employee);
}
connection.Close();
return emplist;
}
public bool EDITCustomer(ICustomerBO bb)
{
bool flag = false;
string ConnectionString = "";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_editemploye";
command.Connection = connection;
SqlConnection conn = new SqlConnection();
command.Parameters.AddWithValue("#id", bb.id);
command.Parameters.AddWithValue("#employeename", bb.empname);
command.Parameters.AddWithValue("#dob", bb.dob);
command.Parameters.AddWithValue("#location", bb.location);
command.Parameters.AddWithValue("#gender", bb.gender);
command.Parameters.AddWithValue("#doj", bb.doj);
command.Parameters.AddWithValue("#experience", bb.experience);
command.Parameters.AddWithValue("#ctc", bb.ctc);
command.Parameters.AddWithValue("#designation", bb.designation);
command.Parameters.AddWithValue("#unithead", bb.unithead);
command.Parameters.AddWithValue("#projectid", bb.projectid);
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if (rowaffected > 0)
{
flag = true;
}
return flag;
}
public bool DeleteEmployee(int bbb)
{
bool flag = false;
string ConnectionString = ;
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_deletemploye";
command.Connection = connection;
command.Parameters.AddWithValue("#id", bbb);
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if (rowaffected > 0)
{ flag = true; }
return flag;
}
public List<ICustomerBO> viewallListsearchBO(int exo)
{
string ConnectionString = "Data Source = ;" +
"Initial Catalog = ;"
+ "User id=;"
+ "Password=password;";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#id", exo);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_searchemployee";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["employeename"].ToString();
DateTime dob = Convert.ToDateTime(reader["dob"]);
string locn = reader["location"].ToString();
string gender = reader["gender"].ToString();
DateTime doj = Convert.ToDateTime(reader["doj"]);
int exp = Convert.ToInt32(reader["experience"]);
int ctc = Convert.ToInt32(reader["ctc"]);
string desg = reader["designation"].ToString();
string head = reader["unithead"].ToString();
int proj = Convert.ToInt32(reader["projectid"]);
ICustomerBO employee = BOFactory.CustomerBOFactory.ADDEMPLOYEE(id, name, dob, locn, gender, doj, exp, ctc, desg, head, proj);
emplist.Add(employee);
}
connection.Close();
return emplist;
}
}
}
====================================================================================================================================using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BOO;
using DAL;
using Types;
namespace DALFactory
{
public class CustomerDALFactory
{
public static ICustomerDAL addcustomer()
{
ICustomerDAL adddal = new CustomerDAL();
return adddal;
}
public static ICustomerDAL LOGIN()
{
ICustomerDAL obj = new CustomerDAL();
return obj;
}
public static List<ICustomerBO> viewalllist()
{
ICustomerDAL cust=new CustomerDAL();
List<ICustomerBO> cust1 = cust.viewallListBO();
return cust1;
}
public static ICustomerDAL EditCustomer()
{
ICustomerDAL d = new CustomerDAL();
return d;
}
public static ICustomerDAL deletecustomer()
{
ICustomerDAL e = new CustomerDAL();
return e;
}
public static List<ICustomerBO> DBBIND()
{
ICustomerDAL obj5 = new CustomerDAL();
List<ICustomerBO> emp1 = obj5.DBbind();
return emp1;
}
public static List<ICustomerBO> viewsearchlist(int exo)
{
ICustomerDAL cust = new CustomerDAL();
List<ICustomerBO> cust1 = cust.viewallListsearchBO(exo);
return cust1;
}
}
}
============================================================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Types;
using BOFactory;
using BLLFactory;
using DALFactory;
namespace miniproject
{
public partial class AddEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
ICustomerBLL bllobj1 = BLLFactory.CustomerBLLFactory.dbind(); //dbind();
List<ICustomerBO> list = bllobj1.dbbind();
DropDownList5.DataSource = list;
DropDownList5.DataTextField = "location";
DropDownList5.DataValueField = "location";
DropDownList5.DataBind();
}
}
protected void TextBox6_TextChanged(object sender, EventArgs e)
{
double a = Convert.ToInt32(TextBox6.Text);
if (a == 0)
{
RangeValidator3.MaximumValue = "3";
RangeValidator3.MinimumValue = "1.5";
RangeValidator3.Type = ValidationDataType.Double;
RangeValidator3.Validate();
if (!RangeValidator3.IsValid)
{
RangeValidator3.ErrorMessage = "Enter CTC between 1.5 and 3";
}
}
else
{
double max = (a * 1.5) + 3;
double min = (a * 1.5) + 1.5;
RangeValidator3.MaximumValue = max.ToString();
RangeValidator3.MinimumValue = min.ToString();
RangeValidator3.Type = ValidationDataType.Double;
RangeValidator3.Validate();
if (!RangeValidator3.IsValid)
{
RangeValidator3.ErrorMessage = "Enter CTC between " + min + " and " + max;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string empname = TextBox1.Text;
DateTime dob = Convert.ToDateTime(TextBox2.Text);
string location = DropDownList5.SelectedItem.Text;
string gender = RadioButtonList3.SelectedItem.Text;
DateTime doj = Convert.ToDateTime(TextBox4.Text);
int experience = Convert.ToInt32(TextBox6.Text);
int ctc = Convert.ToInt32(TextBox5.Text);
string designation = DropDownList4.SelectedItem.Value;
string unithead = DropDownList1.SelectedItem.Text;
int projectid = Convert.ToInt32(DropDownList2.SelectedItem.Text);
ICustomerBLL bllobj = BLLFactory.CustomerBLLFactory.Addcustomer();
ICustomerBO boobj = BOFactory.CustomerBOFactory.Addcustomer( empname,dob, location, gender, doj, experience,ctc,
designation, unithead,projectid);
int rowaffected = bllobj.AddCustomer(boobj);
if(rowaffected>0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "call function", "alert('ADDED SUCCESSFULLY.ID=" + rowaffected + "');", true);
}
else
{
Response.Write("<script>alert('customer not added ')</script>");
}
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TextBox4_TextChanged(object sender, EventArgs e)
{
}
}
}
================================================================================================================================
</tr>
</table>
</asp:Content>
========================================================================================================================================================
using Types;
using DALFactory;
using BOFactory;
using BLLFactory;
namespace miniproject
{
public partial class EditEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
viewdata();
}
}
private void viewdata()
{
List<ICustomerBO> emp = DALFactory.CustomerDALFactory.viewalllist();
GridView1.DataSource = emp;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbid = (Label)GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;
ICustomerBLL bllobj1 = BLLFactory.CustomerBLLFactory.DeleteEmployee();
int id = Convert.ToInt32(lbid.Text);
bool rowaffected = bllobj1.deleteemployee(id);
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
viewdata();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
GridViewRow SelectedRow = GridView1.Rows[e.RowIndex];
Label lbid = (Label)SelectedRow.FindControl("Label1") as Label;
string Name = (SelectedRow.FindControl("TextBox1") as TextBox).Text;
DateTime dob = Convert.ToDateTime((SelectedRow.FindControl("TextBox2") as TextBox).Text);
string Location = (SelectedRow.FindControl("TextBox3") as TextBox).Text;
string gender = (SelectedRow.FindControl("TextBox4") as TextBox).Text;
DateTime doj = Convert.ToDateTime((SelectedRow.FindControl("TextBox5") as TextBox).Text);
int exp = Convert.ToInt32((SelectedRow.FindControl("TextBox6") as TextBox).Text);
int ctc = Convert.ToInt32((SelectedRow.FindControl("TextBox7") as TextBox).Text);
string Designation = (SelectedRow.FindControl("TextBox8") as TextBox).Text;
string Headid = (SelectedRow.FindControl("TextBox9") as TextBox).Text;
int projid = Convert.ToInt32((SelectedRow.FindControl("TextBox10") as TextBox).Text);
int id = int.Parse(lbid.Text);
string name = Name.ToString();
DateTime dob1 = Convert.ToDateTime(dob);
string locn = Location.ToString();
string gen = gender.ToString();
DateTime doj1 = Convert.ToDateTime(doj);
int expr = Convert.ToInt32(exp);
int ctc1 = Convert.ToInt32(ctc);
string desg = Designation.ToString();
string head1 = Headid.ToString();
int proj1 = Convert.ToInt32(projid);
ICustomerBO boobj = BOFactory.CustomerBOFactory.EditCustomer(id, name, dob1, locn, gen, doj1, expr, ctc1, desg, head1, proj1);
ICustomerBLL bllobj = BLLFactory.CustomerBLLFactory.EditEmployee();
bool success = bllobj.editemployee(boobj);
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow SelectedRow = GridView1.SelectedRow;
Label lbid = (Label)SelectedRow.FindControl("Label1") as Label;
string Name = (SelectedRow.FindControl("Label2") as Label).Text;
DateTime dob = Convert.ToDateTime((SelectedRow.FindControl("Label3") as Label).Text);
string Location = (SelectedRow.FindControl("Label4") as Label).Text;
int projid = Convert.ToInt32((SelectedRow.FindControl("Label11") as Label).Text);
int id = Convert.ToInt32(lbid.Text);
Session["EmployeeID"] = id;
Session["EmployeeName"] = Name;
Session["CTC"] = ctc;
Session["DESIGNATION"] = Designation;
Session["HEADID"] = Headid;
Session["PROJECTID"] = projid;
Response.Redirect("Update.aspx");
}
}
}
==================================================================================================================================
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="EditEmployee.aspx.cs" Inherits="miniproject.EditEmployee" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceholder1" runat="server">
<div style="margin: left:25%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("empname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("empname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DateOfBirth">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("dob") %>'></asp:TextBox>
<asp:CommandField EditText="Select" HeaderText="Action" ShowSelectButton="True" />
<asp:CommandField EditText="Delete" HeaderText="Action" ShowDeleteButton="True" />
<asp:CommandField HeaderText="Action" ShowEditButton="True" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
===================================================================================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class DBUtility
{
public static SqlConnection getconnection()
{
SqlConnection dbconnection = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["constr"];
if(settings!=null)
{
string str = settings.ConnectionString;
dbconnection = new SqlConnection(str);
}
return dbconnection;
}
}
}
============================================================================================================================
public int updatesupplier(ISupplierBO objBO)
{
int ret = 0;
SqlConnection conn = DBUtility.getconnection();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_Updatesupplier";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Supplierid",objBO.Suplierid);
cmd.Parameters.AddWithValue("#Companyname", objBO.Companyname);
cmd.Parameters.AddWithValue("#Contactname", objBO.Contactname);
cmd.Parameters.AddWithValue("#Companyaddress", objBO.Companyaddress);
cmd.Parameters.AddWithValue("#City", objBO.City);
cmd.Parameters.AddWithValue("#Country", objBO.Country);
cmd.Parameters.AddWithValue("#Homepage", objBO.Homepage);
cmd.Parameters.AddWithValue("#Contactno", objBO.Contactno);
cmd.Parameters.AddWithValue("#Emailaddress", objBO.Emailaddress);
cmd.Parameters.AddWithValue("#Bankdetails", objBO.Bankdetails);
cmd.Parameters.AddWithValue("#Accountno", objBO.Accountno);
ret = cmd.ExecuteNonQuery();
conn.Close();
return ret;
}
======================================================================================================================================
<connectionStrings>
<add name="constr" connectionString="Data Source=sql01;Initial Catalog=dbtemp;User ID=vishal;Password=mahesh" providerName="System.Data.SqlClient"/>
</connectionStrings>
=====================================================================================================================================
<asp:TemplateField HeaderText="UnitHead">
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Eval("unithead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectID">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Eval("projectid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label12" runat="server" Text="Enter ID to search"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnPageIndexChanging="GridView1_PageIndexChanging" PageIndex="5" AllowPaging="True" PageSize="5">
===================================================================================================================================
using Types;
using DALFactory;
using BOFactory;
namespace miniproject
{
public partial class ViewEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
private void BindData()
{
List<ICustomerBO> emp = DALFactory.CustomerDALFactory.viewalllist();
GridView1.DataSource = emp;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt16(TextBox1.Text);
List<ICustomerBO> empc = DALFactory.CustomerDALFactory.viewsearchlist(x);
GridView2.DataSource = empc;
GridView2.DataBind();
}
}
}
Related
I want to get what I write in the textbox but always get the "" string. I can't find the value when I type something else into the textboxT_T.
Here is the Gridview code:
<div style="margin:0 auto;width:900px;">
<asp:Label ID="USER_header" runat="server"
Text="一.先新增用戶" CssClass="=text-center"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter = "true" Width="900" OnDataBound = "OnDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="工號" SortExpression="BS_ID">
<ItemTemplate>
<asp:Label ID="lblBSID" runat="server"
Text='<%# Eval("BS_ID") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_ID_tb" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="中文姓名" SortExpression="BS_NAME_CHT">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_CHT" runat="server"
Text='<%# Eval("BS_NAME_CHT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_CHT_tb" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="英文姓名" SortExpression="BS_NAME_ENG">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_ENG" runat="server"
Text='<%# Eval("BS_NAME_ENG") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_ENG_tb" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="部門" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:Label ID="lblBS_DEPT" runat="server"
Text='<%# Eval("BS_DEPT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" Width="200" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="btnInsert" runat="server"
onclick="lbInsert_Click" Text="新增" CommandName="Insert"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is the complete code:
private DataSet _dataSet;
private DataSet _dataSetHKTEL;
private DataSet _datasetHKMOBILE;
private string _value;
protected void Page_Load(object sender, EventArgs e)
{
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
//if (Session["key_pass"] == null)
//{
// Response.Write("<script>alert('YOUR ACCESS DENY! 你沒有權限進入此頁面');location.href='Default.aspx';</script>");
//}
}
private void Viewtable()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 BS_ID,BS_NAME_CHT,BS_NAME_ENG,BS_DEPT FROM BS_USER ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateDataTable();
conn.Open();
da1.Fill(finaldata);
this._dataSet = new DataSet();
this._dataSet.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewItnlHKTel()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_TEL_NO,DA_USER FROM DA_ITNL_HK_TEL ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateTable();
conn.Open();
da1.Fill(finaldata);
this._dataSetHKTEL = new DataSet();
this._dataSetHKTEL.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewITNLHKMOBILE()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_PHONE_NO,DA_USER FROM DA_HK_MOBILE ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateMOBILE_HK();
conn.Open();
da1.Fill(finaldata);
this._datasetHKMOBILE = new DataSet();
this._datasetHKMOBILE.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private DataTable GenerateDataTable()
{
DataTable table = new DataTable();
table.Columns.Add("BS_ID", typeof(string));
table.Columns.Add("BS_NAME_CHT", typeof(string));
table.Columns.Add("BS_NAME_ENG", typeof(string));
table.Columns.Add("BS_DEPT", typeof(string));
return table;
}
private DataTable GenerateTable()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_ITNL_HK_TEL", typeof(string));
return table;
}
private DataTable GenerateMOBILE_HK()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_PHONE_NO", typeof(string));
return table;
}
private void ShowData()
{
Viewtable();
GridView1.DataSource = this._dataSet;
GridView1.DataBind();
ViewItnlHKTel();
ADD_HK_TEL.DataSource = this._dataSetHKTEL;
ADD_HK_TEL.DataBind();
ViewITNLHKMOBILE();
ADD_HK_MOBILE.DataSource = this._datasetHKMOBILE;
ADD_HK_MOBILE.DataBind();
}
protected void lbladd_Click(object sender, EventArgs e)
{
//TextBox id = GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox;
////string strBS_ID = (GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox).Text;
//DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
////string strBS_ID = BS_ID_tb.Text;
////string strBS_NAME_CHT = BS_NAME_CHT_tb.Text;
////string strBS_NAME_ENG = BS_NAME_ENG.Text;
//string strBS_DEPT = DEPT_ddl.SelectedItem.Value;
////using (SqlConnection conn = new SqlConnection(this._connectionString))
////{
//// string query = "INSERT INTO BS_USER(BS_ID , BS_NAME_CHT , BS_NAME_ENG , BS_DEPT) VALUES (#BS_ID , #BS_NAME_CHT , #BS_NAME_ENG , #BS_DEPT)";
//// SqlCommand cmd = new SqlCommand(query, conn);
//// cmd.Parameters.Clear();
//// cmd.Parameters.AddWithValue("#BS_ID", strBS_ID);
//// cmd.Parameters.AddWithValue("#BS_NAME_CHT", strBS_NAME_CHT);
//// cmd.Parameters.AddWithValue("#BS_NAME_ENG", strBS_NAME_ENG);
//// cmd.Parameters.AddWithValue("#BS_DEPT", strBS_DEPT);
//// conn.Open();
//// cmd.ExecuteReader();
//// conn.Close();
//// //Response.Redirect("");
////}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = true;
lblinsertuser.Visible = true;
lbCancelSave.Visible = true;
lbInsert.Visible = false;
}
protected void lbCancelSave_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = false;
lbInsert.Visible = true;
}
DataTable Selectindex()
{
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT '請選擇部門' AS BS_NAME , '000' AS BS_ID UNION SELECT BS_NAME , BS_ID FROM BS_DEPT ORDER BY BS_ID ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
}
catch (SqlException exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
finally
{
}
return dt;
}
protected void OnDataBound(object sender, EventArgs e)
{
DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
DEPT_ddl.DataSource = Selectindex();
DEPT_ddl.DataTextField = "BS_NAME";
DEPT_ddl.DataValueField = "BS_ID";
DEPT_ddl.DataBind();
}
protected void lbSave_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert",StringComparison.OrdinalIgnoreCase))
{
GridView GridView1= (GridView)sender;
TextBox BS_ID_tb = (TextBox)GridView1.FooterRow.FindControl("BS_ID_tb");
string str_BS_ID = BS_ID_tb.Text;
TextBox BS_NAME_CHT_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_CHT_tb");
string str_BS_NAME_CHT = BS_NAME_CHT_tb.Text;
TextBox BS_NAME_ENG_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_ENG_tb");
string str_BS_NAME_ENG_tb = BS_NAME_ENG_tb.Text;
DropDownList DEPT_ddl = (DropDownList)GridView1.FooterRow.FindControl("DropDownList1");
string str_DEPT_value = DEPT_ddl.SelectedItem.Value;
InsertData(str_BS_ID, str_BS_NAME_CHT, str_BS_NAME_ENG_tb, str_DEPT_value);
GridView1.ShowFooter = false;
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
}
}
private void InsertData(string BS_ID, string BS_NAME_CHT, string BS_NAME_ENG, string BS_DEPT)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
conn.Open();
string sql = String.Format("Insert into BS_USER VALUES('{0}','{1}','{2}','{3}')", BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_DEPT);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
View state's purpose is simple:
it's there to persist state across postbacks.
That's why you are getting the initial values like empty strings in the gridview. Setting the property EnableViewState="false" force to get the data by rebinding the control, not from the viewstate. To understand view state more, see here.
I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control
i am using sql query to fetch the data from one dropdown list and want to change the second dropdown list by filter data i mean i am selecting the 1st dropdown list and the 2nd drop downlist show all the customer but i want the specific customer by cardcode when i select cardcode.
kindly help, thanks in advance
here is my aspx.cs code
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;
namespace StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
name2 = CardCode.Rows[i]["CntctPrsn"].ToString();
DropDownList2.Items.Add(new ListItem(name2, name2));
}
}
//adapter.Fill(CardCode);
//DropDownList1.DataValueField = "CardCode";
//DropDownList1.DataTextField = "CardCode";
//DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
this.DropDownList2.Text = theReader["CntctPrsn"].ToString();
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
// this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
// protected void Button1_Click(object sender, EventArgs e)
// {
// SqlConnection connection = new SqlConnection();
// connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDataBaseConnectionString2"].ConnectionString;
// connection.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.CommandText = "select * from OOPR";
// cmd.Connection = connection;
// SqlDataAdapter da = new SqlDataAdapter();
// da.SelectCommand = cmd;
// DataSet ds = new DataSet();
// da.Fill(ds, " OOPR");
// SqlCommandBuilder cb = new SqlCommandBuilder(da);
// DataRow drow = ds.Tables["OOPR"].NewRow();
// drow["CardCode"] = TextBox1.Text;
// drow["CardName"] = TextBox2.Text;
// drow["OpprId"] = TextBox3.Text;
// drow["CprCode"] = TextBox4.Text;
// drow["MaxSumLoc"] = TextBox5.Text;
// ds.Tables["OOPR"].Rows.Add(drow);
// da.Update(ds, " OOPR ");
// string script = #"<script language=""javascript"">
// alert('Information have been Saved Successfully.......!!!!!.');
// </script>;";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
// }
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// connection.Open();
SqlCommand insert = new SqlCommand("Insert into OOPR(CardCode, CardName, OpprId, CprCode,MaxSumLoc) values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5 )", connection); //('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.Text + "','" + TextBox4.Text + "')", connection);
insert.Parameters.AddWithValue("#TextBox1", TextBox1.Text);
insert.Parameters.AddWithValue("#TextBox2", TextBox2.Text);
insert.Parameters.AddWithValue("#TextBox3", TextBox3.Text);
insert.Parameters.AddWithValue("#TextBox4", TextBox4.Text);
insert.Parameters.AddWithValue("#TextBox5", TextBox4.Text);
connection.Open();
// connection.CommandType=CommandType.Text;
// connection.commandType=CommandType.Text;
// try
// {
insert.ExecuteNonQuery();
connection.Close();
// }
//catch
//{
// TextBox5.Text = "Error when saving on database";
// connection.Close();
//}
//TextBox1.Text="";
//TextBox2.Text = "";
//TextBox3.Text = "";
//TextBox4.Text="";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
// this.close();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
and here is the apsx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Opportunity No. :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Total Amount Invoiced:
<asp:TextBox ID="TextBox5" runat="server" Width="193px" ></asp:TextBox>
</p>
<p>
Business partner Territory:
<asp:TextBox ID="TextBox6" runat="server" Width="174px" ></asp:TextBox>
</p>
<p>
Sales Employee:
<asp:TextBox ID="TextBox7" runat="server" Width="235px" ></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add"
Width="140px" />
<asp:Button ID="Button2" runat="server" Text="Cancel" Width="149px"
onclick="Button2_Click" />
</p>
</asp:Content>
Put your filtered customer into a DataTable(dt) and fill like this:
DropDownList2.DataTextField = "CustomerName";
DropDownList2.DataValueField = "CustomerID";
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
The list2 will change its value once the list1 trigger the selectedindexchanged event.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
//*******HERE*****//
DropDownList2.DataSource = CardCode;
DropDownList2.DataBind();
DropDownList2.DataValueField = "CardCode";
DropDownList2.DataTextField = "CntctPrsn";
//*******HERE*****//
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
//*******AND HERE*****//
this.DropDownList2.SelectedValue = selected;
//*******AND HERE*****//
}
connection.Close();
}
}
I am having a textbox on my web form. Within this textbox I am using Jquery Auto Complete. I have taken two labels on my web form and trying to hide this label based on the condition I have given in the TextChanged event of the Textbox. But I am not able display the visible one.
This is my aspx page-
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var items=[<%=autotag %>];
$("#TextBox1").autocomplete({
source:items
});
});
</script>
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox></td>
</tr>
<tr><td colspan="2">
<asp:Panel ID="Panel1" runat="server" Visible="False">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label></asp:Panel>
</td></tr>
</table>
My cs page-
public string autotag="";
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
}
}
//This bind1() is for autocomplete.
public void bind1()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
string query="select name from tbl_data_show";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader dr=cmd.ExecuteReader();
dr.Read();
while(dr.Read())
{
if(string.IsNullOrEmpty(autotag))
{
autotag+="\""+dr["name"].ToString()+"\"";
}
else
{
autotag+=", \""+dr["name"].ToString()+"\"";
}
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
//DataTable dt1 = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Please guide me where I am doing wrong?
If am not wrong, please try by setting autopostback = true, change your asp tag line like this,
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1" AutoPostBack="True"></asp:TextBox>
Update
Try your coding in this way,
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
//Panel1.Visible = true;
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
// DataTable dt1 = new DataTable();
// SqlDataAdapter da = new SqlDataAdapter(cmd);
// da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
//if (dt1.Rows.Count > 0)
//{
// if (TextBox1.Text == dr.GetString(0))
// {
// //Label1.Text = "4";
// //Label2.Text = "5";
// Panel1.Visible=true;
// //Label1.Visible = true;
// //Label2.Visible = false;
// }
// else
// {
// //Label2.Text = "5";
// Panel1.Visible = false;
// //Label2.Visible = true;
// //Label1.Visible = false;
// }
//}
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Let me know, if you get struggle with this again.
Autocomplete Using Ajax :
Initially download ajaxcontrolkit from this link, and then add into your project using this link and then add this line into your source page (below to <%# page>)
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
aspx :
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="1"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
//bind1();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["conn"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name from tbl_data_show where " +
"name like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["name"].ToString());
}
}
conn.Close();
return customers;
}
}
}
if you are not setting Lable visibility false anywhere else, try this
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
dt = g1.return_dt("select name from tbl_data_show");
if (dt.Rows.Count > 0)
{
if (TextBox1.Text == dt.Rows[0]["name"])
{
Label1.Text = "4";
Label1.Visible = true;
}
else if (TextBox1.Text != dt.Rows[0]["name"])
{
Label2.Text = "5";
Label2.Visible = true;
}
else
{
Label1.Visible = false;
Label2.Visible = false;
}
}
}
I am creating an application for a asp.net class that I am taking. One of the pages in the application needs to allow a user to search for a specific student via last name or user ID. When the student is found the page should display the students data and his/her class schedule.
I have gotten everything to work except for the class schedule. The approach I have taken (as we learned in class) was to get the query results via the SqlDataReader and bind it to a GridView. This is done in showStudentSchedule().
The query in this function returns the correct results when I test it against the DB I created, but the grid view displaying a students schedule doesn't show up on the page.
//StudentInformation.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="StudentInformation.aspx.cs" Inherits="StudentInformation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
<asp:Label ID="Label6" runat="server" Text="Search by Last Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</p>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:Label ID="Label5" runat="server"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Panel>
</asp:Content>
//StudentInformation.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class StudentInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userStr = TextBox1.Text;
int userInt;
bool isNum = int.TryParse(userStr, out userInt);
string sqlSelectFindUserByName;
if (isNum)
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.ID = '{0}'", userInt);
else
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.LastName LIKE '%{0}%'", userStr);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand commandFindUserByName = new SqlCommand(sqlSelectFindUserByName, connection);
connection.Open();
SqlDataReader readerFindUserByName = commandFindUserByName.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Please make a selection");
while (readerFindUserByName.Read())
DropDownList1.Items.Add(readerFindUserByName["LastName"].ToString());
if (DropDownList1.Items.Count == 2)
DropDownList1.SelectedIndex = 1;
DropDownList1_SelectedIndexChanged(null, null);
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string nameLast = DropDownList1.SelectedItem.Value;
displayStudent(nameLast);
}
private void displayStudent(String nameLast)
{
clearStudentLabel();
int userInt;
bool isNum = int.TryParse(nameLast, out userInt);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName;
sqlSelectFindUserInfoByName = string.Format("SELECT ID, FirstName, LastName, City, Phone FROM Personal_Info WHERE LastName LIKE '%{0}%'", nameLast);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
int i = 0;
while (readerFindUserInfo.Read())
{
Label1.Text = "Student ID: " + readerFindUserInfo["ID"].ToString();
Label2.Text = "First name: " + readerFindUserInfo["FirstName"].ToString();
Label3.Text = "Last name: " + readerFindUserInfo["LastName"].ToString();
Label4.Text = "City: " + readerFindUserInfo["City"].ToString();
Label5.Text = "Phone: " + readerFindUserInfo["Phone"].ToString();
}
connection.Close();
showStudentSchedule(userInt);
}
private void showStudentSchedule(int id)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName = string.Format("SELECT Class_Schedule.Section_ID, Class_Schedule.Course_ID, Class_Schedule.Days, Class_Schedule.Time, CASE WHEN Personal_Info.FirstName IS NULL THEN 'Staff' ELSE (Personal_Info.LastName + Personal_Info.FirstName) END AS Name FROM Class_Schedule JOIN Student_Enrollment ON Class_Schedule.Section_ID = Student_Enrollment.Section_ID JOIN Personal_Info ON Class_Schedule.Instructor_ID = Personal_Info.ID WHERE Student_Enrollment.Student_ID = {0}", id);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
GridView1.DataSource = readerFindUserInfo;
GridView1.DataBind();
/*
string connectionString = "Data Source=LocalHost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa_0001";
string commandString = "Select * from Customers";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(commandString);
conn.Open();
command.Connection = conn;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();
*/
}
private void clearStudentLabel()
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
Label5.Text = "";
}
}
Try this out:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand(sqlSelectFindUserByName);
connection.Open();
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();