Hide gridview button when status id not equal to 1? - c#

I have a function to load gridview1 and i want to view grid view button coloumns that are at coloumn 7 and 8 only when M_Status from query is equal to 1 , their are multiple records against m_id=2 having m_status equal to 2 , 1, 3 but i want to show approve and deny buttons only against m_id =1
private void loadvisitor()
{
con1 = new SqlConnection(constring1);
string seelctquery = "SELECT M_Status,d.MD_ID , d.MD_Visitor_Name,d.MD_Visitor_Cell, d.MD_Visitor_Company,s.M_StatusName, p.purpose_name , m.M_DateTime FROM Vms_Meeting M left outer join Vms_MeetingD d on m.M_ID= d.M_ID left outer join Vms_Purpose p on m.Purpose_ID= p.purpose_id inner join vms_MeetingStatus as s on d.M_Status = s.M_Status WHERE m.M_ID=2 order by m.M_ID desc;";
da = new SqlDataAdapter(seelctquery, con1);
SqlCommand cmd = new SqlCommand(seelctquery, con1);
if (con1.State == ConnectionState.Closed)
{
con1.Open();
}
dr = cmd.ExecuteReader();
ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
if (dr.HasRows)
{
while (dr.Read())
{
string stid = (string)dr["M_Status"];
if (stid == "1")
{
}
}
}
con1.Close();
}

Related

Loop on each item of a dataRow and group them by a primary key column

I am returning a dataRow from SQL server that contains appointments: Subject, Starting date, Ending date and Channel id.
I need to loop on each item of the dataRow to be able to group the items of a specific channel id in a separately to be able to add them to ultraGanttView.
The following code is working correctly to bind the data to a UltreMonthViewSingle.
So what i need to be able to bind the data in a ganttView is to group them by project which is the channel id in my case.
private void FillCalendar()
{
string query = #"select rs.[Planned Date in] as pdin,rs.[Planned Date out] as pdout, CONCAT(cn.Name,' ',ps.[First Name],' ',ps.[Last Name]) as subj, cn.[ID]
from [dbo].[Reservations] rs
inner join [dbo].[Person] ps on rs.[Person ID] = ps.ID
inner join [dbo].[Channel] cn on rs.[Channel ID] = cn.ID";
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
//return reservations datatable
DataTable table = new DataTable();
SqlDataAdapter adp2 = new SqlDataAdapter(query, conn);
adp2.Fill(table);
//bind appointments
Appointment appointment;
DateTime dateIn, dateOut;
String subj;
foreach (DataRow dataRow in table.Rows)
{
dateIn = DateTime.Parse(dataRow["pdin"].ToString());
dateOut = DateTime.Parse(dataRow["pdout"].ToString());
dateIn.ToString("dd-MMMM-yyyy");
subj = dataRow["subj"].ToString();
appointment = this.ultraCalendarInfo1.Appointments.Add(dateIn, dateOut, subj);
}
}
What should i add to the loop so it can work?
This is a documentation how to bind data in ganttView GanttView Binding
Thank you
This is what i have done and it is working.
private void BindGantt()
{
this.ultraGanttView1.CalendarInfo = this.ultraCalendarInfo1;
string query = "select rs.[Channel ID],c.Name from[dbo].[Reservations] rs inner join[dbo].[Channel] c on rs.[Channel ID] = c.ID group by rs.[Channel ID],c.Name";
DataTable dt = new DataTable();
DataTable dc = new DataTable();
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DateTime dateFrom;
TimeSpan duration;
string subject;
int id;
//get the channels' id that have reservations
for (int j = 0; j < dt.Rows.Count; j++)
{
id = Convert.ToInt32(dt.Rows[j].ItemArray[0].ToString());
dc = GetChannelsReservations(id);
//get the info of all the reservations for a channel
ultraCalendarInfo1.Tasks.Add(DateTime.Now, TimeSpan.FromDays(0), dt.Rows[j].ItemArray[1].ToString());
for (int i = 0; i < dc.Rows.Count; i++)
{
dateFrom = Convert.ToDateTime(dc.Rows[i].ItemArray[0]);
TimeSpan.TryParse(dc.Rows[i].ItemArray[1].ToString(),out duration);
subject = dc.Rows[i].ItemArray[2].ToString();
ultraCalendarInfo1.Tasks[j].Tasks.Add(dateFrom, duration, subject);
}
}
}
private DataTable GetChannelsReservations(int id) {
string query = #"select rs.[Planned Date in],DATEDIFF(DAY, rs.[Planned Date in],rs.[Planned Date out]) as TimeSpan,c.Name+' '+p.[First Name]+' '+p.[Last Name],c.Name
from[dbo].[Reservations] rs
inner join[dbo].[Channel] c on rs.[Channel ID] = c.ID
inner join[dbo].[Person] p on rs.[Person ID] = p.ID
where rs.[Channel ID] ="+id;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}

Invalid columns names Insert statement

I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.
That is the error that I get:
Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.
Can you help me? I think the problem is in the insert statement
Thanks
public void userSales()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userSales();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userSales();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
cmd.Parameters.AddWithValue("#Activity_ID", txtActivity.Text.Trim());
cmd.Parameters.AddWithValue("#Date", ftxtDate.Text.Trim());
cmd.Parameters.AddWithValue("#Quotation_Number", ftxtQno.Text.Trim());
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Quantity", ftxtQuantity.Text.Trim());
cmd.Parameters.AddWithValue("#valueGBR", ftxtvalueGBR.Text.Trim());
cmd.Parameters.AddWithValue("#valueEUR", ftxtvalueEUR.Text.Trim());
cmd.Parameters.AddWithValue("#weightedValue",ftxtweightedValue.Text.Trim());
cmd.Parameters.AddWithValue("#Rate", ftxtRate.Text.Trim());
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#estDecisionDate", ftxtestDecisionDate.Text.Trim());
cmd.Parameters.AddWithValue("#PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userSales();
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
}
}
}
Your Select Statement is executing this...
SELECT SalesActivity.Activity_ID
,SalesActivity.DATE
,SalesActivity.Quatation_Number
,CUSTOMER.Customer_Name
,PRODUCTS.Machine_Model
,SalesActivity.Quantity
,SalesActivity.valueGBR
,SalesActivity.valueEUR
,SalesActivity.Rate
,SalesActivity.weightedValue
,STATUS.STATUS
,SalesActivity.estDecisionDate
,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.
change this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
to this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #estDecisionDate, #PromisedDeliveryDate)", con);
and remove the following lines...
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
The insert should now work.

changing value of cell on condition in gridview - c#

I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}

Display Crystal Report Viewer in ASP.NET

I'm having some trouble in CrystalReport ASP.NET.
I'm creating a DataSet in ASP.NET and I want to export it to CrystalReport.rpt using ADO.NET(xml). But it fails. When I make a new connection and put an attribute column in the report, the Main Report Viewer in Crystal Report shows the wrong result. I compile the sql query in Oraclesqldevelop, the result is fine and doesn't have any problems. I want to click a button and show the report.
This is my code :
protected void btnsumbit_Click(object sender, EventArgs e)
{
lblerror.Text = "";
if (txtdari.Text == "" || txtdari.Text == null || txtsampai.Text == "" || txtsampai.Text == null)
{
lblerror.Text = "Tanggal Harus Diisi !!!";
}
else
{
DateTime dt1 = Convert.ToDateTime(txtdari.Text);
DateTime dt2 = Convert.ToDateTime(txtsampai.Text);
if (dt1.Date > dt2.Date)
{
lblerror.Text = "Format Tanggal yang Dimasukkan Salah !!!";
}
else
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = connectionstring;
conn.Open();
string sql = "SELECT c.SUB_DISTRIBUTOR , c.MID , c.REKNO , b.ID, b.TERMINAL_ID , b.TANGGAL , b.KETERANGAN , b.DEBIT , b.KREDIT , b.SALDO , b.REFF_NO,b.PRODUK,b.NO_PELANGGAN, b.SN_ID , b.STATUS from MERCHANT c JOIN DAILY b ON (b.REKENING_NO = c.REKNO) where TANGGAL between TO_DATE('"+txtdari.Text+"','mm-dd-yyyy') AND TO_DATE('"+txtsampai.Text+"','mm-dd-yyyy')";
OracleCommand cmd = new OracleCommand(sql, conn);
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXmlSchema("C:\\Users\\Henz\\Documents\\Visual Studio 2012\\Projects\\LPI\\LPI\\Files\\Sample.xml");
conn.Close();
Response.Redirect("plot.aspx");
}
}
}
As your description, I can understand that there is not any error happened. The main issue is your result is not like your expectation. So I think you should check again Parameter of your command. Please try with below code :
DateTime dt1 = Convert.ToDateTime(txtdari.Text);
DateTime dt2 = Convert.ToDateTime(txtsampai.Text);
////////ARI DATE/////////
OracleParameter fromDateParameter = new OracleParameter();
fromDateParameter.OracleDbType = OracleDbType.Date;
fromDateParameter.Value = dt1;
////////SAMPAI DATE/////////
OracleParameter toDateParameter = new OracleParameter();
toDateParameter.OracleDbType = OracleDbType.Date;
toDateParameter.Value = dt2;
this.oracleDataAdapter4.SelectCommand = new OracleCommand("SELECT c.SUB_DISTRIBUTOR , c.MID , c.REKNO , b.ID, b.TERMINAL_ID , b.TANGGAL, b.KETERANGAN , b.DEBIT , b.KREDIT , b.SALDO , b.REFF_NO,b.PRODUK,b.NO_PELANGGAN, b.SN_ID , b.STATUS from MERCHANT c JOIN DAILY b ON (b.REKENING_NO = c.REKNO) where TANGGAL BETWEEN :fromDateParameter AND :fromDateParameter)”, conn);
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.SelectCommand.Parameters.Add(fromDateParameter);
da.SelectCommand.Parameters.Add(toDateParameter);
DataTable dt = new DataTable();
da.Fill(dt);

mysql parameters passing not implementing asp.net

I have 3 tables 1>disease_table [columns=] (disease_id,disease_name)2>symptom_table [columns=] (symptom_id,symptom_name)3>disease_symptom [columns=] (disease_id,symptom_id)
there is a checkboxlist on my web page which has symptoms where text=fever, value='fever'..and so on but the problem is that I get no output when I pass parameter to the sql stmt., it doesn't give any output.Also if I pass static parameter (if I choose to pass all the available symptoms) it gives me repeated disease names.
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["myconstring"].ConnectionString);
connection.Open();
symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());
Label3.Text = symptoms;
MySqlCommand cmd = new MySqlCommand("select d.dname from disease d inner join diseasesymptom ds on ds.did = d.did inner join symptom s on s.sid = ds.sid where s.sname in (#pSymptoms)", connection);
cmd.Parameters.AddWithValue("#pSymptoms", symptoms);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = connection;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
sql stmt :
selectd.name, d.disease_id
from Disease d
inner join DiseaseSymptom ds on ds.disease_id = d.disease_id
inner join Symptom s on s.symptom_id = ds.symptom_id
where s.name in ('Fever');
output: if I pass all the parameters(static) then I get all available diseases multiple times (e.g :if disease 'd1' has 2 symptoms and I choose 2 of those symptoms that disease 'd1' is displayed twice)

Categories