Hope You all Are Fine
Can any one help me kindly i have a grid view that fetch tha record from database but show all the previous data which i entered by the grid but now i want to show the all data which i entering till the pageload even called, when page load that should not show all the entered records.
Thanks in Advance
Here is my code behind work
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("select distinct T1.SlpCode,T1.SlpName,T3.StepId,T3.Descript from OSLP T1 left join OPR1 T2 on T1.SlpCode=T2.SlpCode right join OOST T3 on T3.StepId=t2.Step_Id ", connection);
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
If you want to keep the grid empty on page load event, then do not write the code to bind it on Page Load event, instead write the code on"Add Button" click event(if that's what you want).
For showing empty record Grid You can Use EmptyDataTemplate.
For more you can try this Link
Related
i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx
I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}
As title said it all anyway I have a table is sql-server products.
Which has product id, name,price and cetegory.
what i did is i get data into 1st GridView category wise, and what i want is when i checked that particular row or multiple row and click select button it shuld show product name and price in 2nd gridview.
But what its do is it override the next selected item to previously selected item in 2nd gridview and shows onlu one row not multiple selected items.
can anybody help me ??
here is a code
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;
if (chbox.Checked == true)
{
string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "select prod_name,price from products where prod_id = '" + GridView1.Rows[i].Cells[1].Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
}
You binded the grid too many times.
protected void Button1_Click(object sender, EventArgs e) {
List<string> checkedIDs = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++) {
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;
if (chbox.Checked == true)
{
checkedIDs.Add("'" + GridView1.Rows[i].Cells[1].Text + "'");
}
}
string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "select prod_name,price from products where prod_id in (" + string.Join(",", checkedIDs.ToArray()) + ")";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
I'm new to c#, as in.
I'm currently working on a search function in c# using 3 DropDownLists and a submit button. When a user select an item on DropDownList and click submit, it will print the table for the respective selection.
There are 3 DropDownLists:
a province,
city,
specialization.
This will search the available doctors that suits the selection. For example I choose province1 on 1st DropDownList, city1 on the 2nd and a psychologist on 3rd, when the submit button is fired, it will print the available doctors that is in province1, city1 and has a specialization of psychologist.
I already have a code, still figuring it out but, when i click the submit button, nothing is happening. Can someone help me?
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
ddlProvince.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_specialization", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPEC_NAME";
ddlSpec.DataValueField = "SPEC_CODE";
ddlSpec.DataBind();
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void btnSub_Click(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_doctors");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where Province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
}
}
Make change in this line of code which is in submit button click function
Correct code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
because as you see your code query is incorrent have look to your code which is incorrect
Wrong code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where (" + ddlProvince.SelectedItem.ToString() + " ", conn);
Edit:
if you want to display record that you got in DataTable you either need loop through the records or you need to use GridView for that...i think you miss that thing
in above one after where clause you miss the name of the filed you need to made filter on... i have written update code by modifying that condition.
See MSDN for GridView.
You said that after clicking submit, nothing happend. But in btnSub_Click I didn't see anything that displaying the result or changing anything on the page. You should bind dt to some control like a gridview etc.
I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}
you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.