Calendar to DataGrid - c#

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!

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.

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;

to clear the data of datagridview

I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}

How to display SQL search results in a datagrid using WPF

private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}

Fetching and displaying tables on database

I'm just starting out at asp.net c# and I have been given a task to generate the available doctors upon the given values in a drop-down list.
I have 3 drop-down lists, (1)PROVINCE, (2)CITY, (3)SPECIALIZATION and a search button.
After the user selects the values of 3 drop-down lists and hits the search button it will print a table containing the available doctor.
I know that the key is on the search button, but I don't exactly know what to put under the search button. Can you help me out please?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
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();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
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();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
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 distinct emed_accredited_providers.SPECIALIZATION from emed_accredited_providers inner join emed_doctors_hospitals on emed_accredited_providers.DOCTOR_CODE = emed_doctors_hospitals.DOCTOR_CODE where CITY_CODE =#ccode", 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 = "SPECIALIZATION";
ddlSpec.DataValueField = "SPECIALIZATION";
ddlSpec.DataBind();
}
protected void btnDocs_Click(object sender, EventArgs e)
{
}
}
}
string query = string.Empty;
if (ddlProvince.SelectedIndex != -1)
{
query = query + " and PROVINCE_CODE=" + ddlProvince.SelectedValue;
}
if (ddlCity.SelectedIndex != -1)
{
query = query + " and CITY_CODE=" + ddlProvince.SelectedValue;
}
if (ddlSpec.SelectedIndex != -1)
{
query = query + " and SPECIALIZATION=" + ddlProvince.SelectedValue;
}
string tQuery = "Select * from Doc";
if (query.Length > 0)
{
query = query.Remove(0, 4);
tQuery = tQuery + query;
}
// Exeucate -- tQuery
// Modify table name or field name.
get the selected values from the drop down list
pass the selected values to your search function. (It depends on your logic, I mean if user select values from only one drop down, from only two drop down your search query may differ).
get the return values from your search function and bind it to your table (grid view)
Also have a look at the DropDownList.SelectedIndex Property
to bind the gridview you can do something similar to this
private void BindGrid ()
{
var dt = new DataTable();
var connection = new SqlConnection(YOUR CONNECTION);
try
{
connection.Open();
var query = "YOUR SEARCH QUERY";
var sqlCmd = new SqlCommand(query, connection);
var sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
//
}
finally
{
connection.Close();
}
}

Categories