When entering data does not update the text box - c#

Hello friends I am writing to pull information from the base TextBox and I want to update the database through the TextBox , but when I enter the new value is the old value does not always save the new value
Code behind
protected void Page_Load(object sender, EventArgs e)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
Button Click Event
string ust = Request.QueryString["ID"].ToString();
SqlConnection baglanti = new SqlConnection(ConnectionString3);
baglanti.Open();
string kayit = "update pkategori set Tanim=#Tanim where Id=#Id";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#Tanim", baslik.Text);
komut.Parameters.AddWithValue("#Id", ust);
komut.ExecuteNonQuery();
baglanti.Close();

Simple, just wrap your code in Page_Load in a !IsPostBack-check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
}
Otherwise you are loading the text from the database and the changed value is overwritten.

Related

How do I add a column to DataGridView through code?(Using C# Windows Application) [duplicate]

I am fresher in c# language .Now my project is to fetch the data from database to datagridview and add edit and delete column.
i had a 5 field(id,name,degree,college,city) in the table student
here my code:
MySqlConnection connection = new MySqlConnection("SERVER=hostaddress","DATABASE=DTBS","UID=UID","PASSWORD=PWDS");
MySqlCommand command = new MySqlCommand("SELECT * from student;", connection);
connection.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(dataTable);
dataGridView1.DataSource = dataTable;
now i need the help on adding an edit and delete column on the datagridview.
when i clicking an edit on datagridview i need to get that rows data on my form 2 i did not understand what is it and how can i do it. i am searching more on google. but i did not get an clear explanation about it help me in some coding.
Try this coding:
String MyConnection = "SERVER=********;" +
"DATABASE=dtabs;" +
"UID=usrname;" +
"PASSWORD=pswrd;" + "Convert Zero Datetime = True";
public string id { get; private set; }
private void Form1_Load(object sender, EventArgs e)
{
data();
//Edit link
DataGridViewLinkColumn Editlink = new DataGridViewLinkColumn();
Editlink.UseColumnTextForLinkValue = true;
Editlink.HeaderText = "Edit";
Editlink.DataPropertyName = "lnkColumn";
Editlink.LinkBehavior = LinkBehavior.SystemDefault;
Editlink.Text = "Edit";
dataGridView1.Columns.Add(Editlink);
//Delete link
DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
Deletelink.UseColumnTextForLinkValue = true;
Deletelink.HeaderText = "delete";
Deletelink.DataPropertyName = "lnkColumn";
Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
Deletelink.Text = "Delete";
dataGridView1.Columns.Add(Deletelink);
}
//Make it as public for that only we call data() in form 2
public void data()
{
MySqlConnection connection = new MySqlConnection(MyConnection);
MySqlCommand command = new MySqlCommand("SELECT * from student;", connection);
connection.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(dataTable);
dataGridView1.DataSource = dataTable;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Refresh();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MySqlConnection conn = new MySqlConnection(MyConnection);
conn.Open();
//edit column
if (e.ColumnIndex == 5)
{
id = Convert.ToString(dataGridView3.Rows[e.RowIndex].Cells["id"].Value);
Form2 frm2 = new Form3(this);
fm2.a = id;
fm2.Show();
dataGridView1.Refresh();
//delete column
if (e.ColumnIndex == 6)
{
id = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["id"].Value);
MySqlDataAdapter da = new MySqlDataAdapter("delete from student where id = '" + id + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.Refresh();
}
}
FORM 2:
public partial class Form2 : Form
{
// for this we can reload after closing the form 2 the datagridview get refresh
Form1 _owner;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 owner)
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
}
String MyCon = "SERVER=*******;" +
"DATABASE=dtbas;" +
"UID=userid;" +
"PASSWORD=paswrd;" + "Convert Zero Datetime = True";
public string a
{
get { return txtid.Text; }
set { txtid.Text = value; }
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.data();
}
private void Form2_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyCon);
con.Open();
MySqlCommand Com = new MySqlCommand("Select * from student where id ='" + txtid.Text + "'", con);
MySqlDataReader dt = Com.ExecuteReader();
if (dt.Read())
{
// i assume (id textBox as txtid),(name textbox as txtname),(degree textbox as txtdegree),(college textbox as txtcollege),(city textbox as txtcity)
txtid.Text = dt.GetValue(0).ToString();
txtname.Text = dt.GetValue(1).ToString();
txtdegree.Text = dt.GetValue(2).ToString();
txtcollege.Text = dt.GetValue(3).ToString();
txtcity.Text = dt.GetValue(4).ToString();
con.Close();
}
//button in form2 to save it in the database. (button as btnsave)
private void btnsave_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyCon);
con.Open();
string query = string.Format("Update student set id='" + txtid.Text + "' , name='" + txtname.Text + "' , degree='" + txtdegree.Text + "' , college='" + txtcollege.Text + "' , city='" + txtcity.Text + "'where id='" + txtid.Text + "'");
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
}
Refrence:http://www.dotnetsharepoint.com/2013/07/how-to-add-edit-and-delete-buttons-in.html
it helps you.

why i get this error when i do allow paging True The data source does not support server-side data paging

I had opened a related topic before, but I realized the problem now. When I set allow paging correctly in the properties of gridview in web form.aspx, I get this error. I don't know if the codes I wrote in aspx.cs browser cause this problem, please help
'''
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GVbind();
}
}
void clear()
{
txtName.Text = "";
txtPhone.Text = "";
txtAdd.Text = "";
}
protected void btnInsert_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[idus] VALUES ('" + txtName.Text + "', '" + txtPhone.Text + "', '" + txtAdd.Text + "')", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
Response.Write("<script>alert('Data inserted successfully') </script>");
con.Close();
}
GVbind();
clear();
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"DELETE FROM [dbo].[idus]
// WHERE [ID]='" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data deleted successfully");
// con.Close();
//}
//protected void btnUpdate_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[idus]
// SET[ID] = '" + txtID.Text + "',[name] = '" + txtName.Text + "',[phone] = '" + txtPhone.Text + "',[address] = '" + txtAdd.Text + "' WHERE [ID]= '" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data updated successfully");
// con.Close();
//}
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GVbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string phone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
con.Open();
SqlCommand cmd = new SqlCommand("update [dbo].[idus] set name='" + name + "', phone='" + phone + "', address='" + address + "' where ID = '" + ID + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been updated') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GVbind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
con.Open();
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand("delete from [dbo].[idus] where ID='" + id + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been deleted') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void DisplayData()
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[idus]", con);
con.Open();
da.Fill(dt);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GVbind();
'''
enter image description here
enter image description here
You are assigning the GV a "reader", and you can't use a reader - you have to fill a table, or use some other ennumberable collection. Say like a data table.
So, this code:
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
Change to :
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
Datatable dt = new dt();
dt.load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
So, while you can "shove" the GV to a reader directly? If you going to use paging, then you can't shove into the GV a reader - since paging does not work with a non innumerable type of data set (like a reader).
So, just load up a data table. And note how I did not even need a data adaptor to load up a data table (the data table has a .Load command for you. (so, you can shorten your other code this way also).

How to save the name of dropdownlist instead of its ID?

I m been working on a project in which i m facing an issue
I m having two drop down list which are Select category (ddlcategory) and select subcategory (ddlsubcategory) here are they
When I'm saving the data i m getting the ID saved into my database instead of category name and subcategory name Here is my database values :
Here is my back code i have implemented :
String constr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True";
string query = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategoryDropdown();
}
}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
Response.Redirect("http://localhost:50550/Online Tours and Travels/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Session.Clear();
Response.Redirect("http://localhost:50550/Online Tours and Travels/Admin Panel/LoginForm.aspx");
}
protected void BindCategoryDropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from category", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlcategory.DataSource = ds;
ddlcategory.DataTextField = "Cat_name";
ddlcategory.DataValueField = "Cat_id";
ddlcategory.DataBind();
ddlcategory.Items.Insert(0, new ListItem("--Select--", "0"));
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlcategory_SelectedIndexChanged(object sender, EventArgs e)
{
int categoryid = Convert.ToInt32(ddlcategory.SelectedValue);
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from subcategory where catid=" + categoryid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlsubcategory.DataSource = ds;
ddlsubcategory.DataTextField = "subcatname";
ddlsubcategory.DataValueField = "subcatid";
ddlsubcategory.DataBind();
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
String pathName1 = "~/packageimages/" + Path.GetFileName(fileuploadpic1.PostedFile.FileName);
String pathName2 = "~/packageimages/" + Path.GetFileName(fileuploadpic2.PostedFile.FileName);
String pathName3 = "~/packageimages/" + Path.GetFileName(fileuploadpic3.PostedFile.FileName);
query =
"insert into package(packname,catid,categoryname,subcatname,packageprice,pic1,pic2,pic3,detail) values('"+txtpackagename.Text+"','"+txtcategoryid.Text+"','"+ddlcategory.Text+"','"+ddlsubcategory.Text+"','"+txtpackageprice.Text+"','"+pathName1+"','"+pathName2+"','"+pathName3+"','"+txtdetails.Text+"') ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
fileuploadpic1.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic1.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic2.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic3.FileName));
txtpackagename.Text = "";
txtcategoryid.Text = "";
txtpackageprice.Text = "";
txtdetails.Text = "";
string message = "Package Added !!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Please do help ! Thank You
answering your question - you need to use
ddlcategory.SelectedItem.Text not ddlcategory.Text
But as suggested, first do learn about query parameters
for example here
And about using statement for example here
The name of a Control gets generated by aspnet itself. Depending where in the control tree a Control is located, it could become something like this:
ctl00$ContentPlaceHolder1$ctl00$TextBox1
But if you really want to get the name, you can use UniqueID.
string controlName = TextBox1.UniqueID;

Gridview Edit Delete and Update in ASP.NET

I tried Implementing the code for Edit and Update button for gridview but it doesn't seems working for me. Add button working well but delete and update do not working. During runtime error the error is "An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Unknown column 'p001' in 'where clause'"
Note: type of P_Id in the database is varchar(10), name varch(100), level varchar, value varchar
public partial class ManagePractice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
TextBox txtID = (TextBox)GridView1.FooterRow.FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.FooterRow.FindControl("txtSubject");
RadioButtonList Level = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList1");
AddPractice(txtID.Text.Trim(), txtSubject.Text.Trim(), Level.Text.Trim(), PType.Text.Trim());
BindData();
}
private void AddPractice(string P_Id, string subject, string level, string type)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "insert into practice(P_Id,name,level,value) values ('" + P_Id + "','" + subject + "','" + level + "','" + type + "')";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select P_Id,level,name,value from practice", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = (GridView1.DataKeys[e.RowIndex].Value.ToString ());
DeletePractice(id);
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubject");
// TextBox Level1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtlevel");
// TextBox PType1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPType1");
RadioButtonList Level = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
UpdatePractice( txtID.Text , txtSubject.Text, Level.Text, PType.Text);
GridView1.EditIndex = -1;
BindData();
}
private void UpdatePractice( string P_Id, string name, string level, string value)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + " WHERE P_Id=" + P_Id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void DeletePractice(string id)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "DELETE FROM practice WHERE P_Id=" + id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
First sight:
Since P_Id column has VARCHAR(10) datatype, I figured out you forget to include some additional apostrophes on UPDATE & DELETE clause. The correct form of SQL statements should be this (notice additional apostrophe signs around P_Id column):
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + "' WHERE P_Id= '" + P_Id + "'";
and
string query = "DELETE FROM practice WHERE P_Id='" + id + "'";
Only string values require apostrophes around them, numbers do not.

Calendar to DataGrid

I really can't seem to nail down what I need to accomplish my task. I have a DataGrid in asp.net in VS2010 this displays data from a SQL database , in one of these fields is a "StartDate".
Also I have a simple Calendar running . What I would like is to be able to update my DataGrid by passing it the selected date and using that as the "StartDate" to call a selection on the DataGrid , so only records with that start date will appear.
I have looked on-line but the examples are very old or are a bit confusing .
If anyone can layout the steps (if possible sample code) involved to achieve this i would be grateful or any resources or examples you have come across though I have searched for a while, hence the post!.
Thanks.
What i have currently is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{
// CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
}
protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["Start"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["Start"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}
private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from Bookings where Start ='" + Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0 )
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
GridView1.DataSource = dsSelDate;
GridView1.DataBind ();
}
}
}
What am i doing wrong?.
EDIT__
Finally it works , Here is my code if anyone has similar issue/requirement.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=BBC-PC-S054683;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{ // CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC-Name;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
BindGrid();
}
}
private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Bookings";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
String Date = Calendar1.SelectedDate.ToLongDateString();
SqlConnection con = new SqlConnection(strConnection);//put connection string here
SqlCommand objCommand = new SqlCommand("SELECT * FROM Bookings where Date = '" + Date + "'", con);//let MyTable be a database table
con.Open();
SqlDataReader dr = objCommand.ExecuteReader();
GridView.DataSource = dr;
GridView.DataBind();
}
You need to filter your DataGridView.
try
{
myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
DataAdapter.SelectCommand.Connection = myConnection;
DataAdapter.TableMappings.Clear();
DataAdapter.TableMappings.Add("Table", "TableName");
DataAdapter.Fill(myDataSet);
myDataView = new DataView(myDataSet.Tables["TableName"], "TIMESTAMP >= '" +
Convert.ToDateTime(fromDate) + "' AND TIMESTAMP <= '" +
Convert.ToDateTime(toDate) + "'", "TIMESTAMP", DataViewRowState.CurrentRows);
dgv.DataSource = myDataView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
TIMESTAMP is a column in my DataGridView.
Note: This is just a code snippet!

Categories