I am trying to make the dropdownlist I have already created inside of the edit page of a formview start on the value previously selected from the sql database for the current user.
So far I have the code to populate the drop down list working correctly:
protected void ddlSelect_Init(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix, Number, ClassSection, Location, StartTime, EndTime, ClassDay, Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, Capacity, GPAReqAbove1, GPAReqBelow1, CreditReqAbove30, CreditReqBelow30, ClassCredit, IsTransfer, SLN FROM Classes");
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
ddlSelect.DataSource = dt;
ddlSelect.DataTextField = "PN";
ddlSelect.DataValueField = "SLN";
ddlSelect.DataBind();
con.Close();
}
Where SLN is the unique value for each item in the dropdownlist and PN is the background information for each item in the dropdownlist. I want the item that is highlighted to be the PN that corresponds to what that specific user already has stored in the database. The problem is that when I try to have that value selected I am using:
protected void FVStudentClass_ModeChanging(object sender, FormViewCommandEventArgs e)
{
if (FVStudentClass.CurrentMode != FormViewMode.Edit)
return;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ReinstatementCS"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Prefix + Number + ', Section: ' + CAST(ClassSection AS VarChar) + ', Location: ' + Location + ', Start Time: ' + StartTime + ', End Time: ' + EndTime + ', Days: ' + ClassDay + ', Credits: ' + CAST(ClassCredit AS VarChar) AS PN, SLN FROM Classes JOIN StudentClass on SLN = SCClass WHERE SCWSUID = " + Request.QueryString["ALWSUID"]);
myCommand.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddlSelect = new DropDownList();
ddlSelect = FVStudentClass.FindControl("ddlSelect") as DropDownList;
if (ddlSelect != null)
{
ddlSelect.DataSource = dt;
ddlSelect.Items.FindByText(dt.Rows[0]["PN"].ToString()).Selected = true;
}
con.Close();
}
but I'm still stuck because the dropdownlist does not start out with the saved value being selected. Do you know how to fix this? Am I using the wrong command (Should I use something besides ModeChanging)?
Thanks!
Try implementing the logic to select the DropDownList item on the FormView DataBound event, the ModeChanging event happens before the mode is actually changed.
You should be able to just set ddlSelect.SelectedValue to the value you want the dropdown to select.
ddlSelect.SelectedValue = dt.Rows[0]["PN"].ToString();
Related
I am working on a code in C# where I used OLEDB connection string to connect MS access database.
I have a form where I show data from database in datagridview on some criteria.
Below are criteria:
a) Person (come from database in
b) Process (come from database in textbox)
c) From Date (Datetimepicker)
d) To Date (Datetimepicker)
Result what I want: first I select person and than process and than From Date and then To date and click on View Button. which should show data from MS-Access based on above criteria I selected.
I've tried below methods:
Code:
1. For Person and Process filter:
DataView DV = new DataView(dt1);
DV.RowFilter = string.Format("[Person] LIKE '%{0}%'", textBox5.Text);
dataGridView1.DataSource = DV;
For Date Time between Two date I tried many and Google lots but not find answer. I tried below:
a)
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
string queryString = "";
queryString = "SELECT * FROM Table1 WHERE dob BETWEEN #startdate AND #enddate";
System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, con);
sqlCmd.Parameters.Add("#startdate", System.Data.SqlDbType.Date).Value = textBox7.Text;
sqlCmd.Parameters.Add("#enddate", System.Data.SqlDbType.Date).Value = textBox8.Text;
System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
System.Data.DataSet dataSet = new System.Data.DataSet();
dataAdapter.Fill(dataSet);
GridView1.DataSource = dataSet;
GridView1.DataBind();
b)
string FD = "";
FD = dateTimePicker4.Value.ToString("dd-MM-yyyy");
string TD = "";
TD = dateTimePicker5.Value.ToString("dd-MM-yyyy");
connection.Close();
connection.Open();
OleDbCommand command123 = new OleDbCommand();
command123.Connection = connection;
string query123 = "select * from Table1 where [P Date] between date '"# + dateTimePicker4.Text.ToString() + #"' and date '"# + dateTimePicker5.Text.ToString() + #"'"
command123.CommandText = query123;
OleDbDataAdapter da123 = new OleDbDataAdapter(command123);
DataTable dt123 = new DataTable();
da123.Fill(dt123);
dataGridView1.DataSource = dt123;
c)
DataTable dt = new DataTable();
da.Fill(dt);
DataView DV = new DataView(dt1);
DV.RowFilter = string.Format("[P Date] >=" + textBox7.Text + " and <" + textBox8.Text + "");
dataGridView1.DataSource = DV;
d)
DataTable dt1 = new DataTable();
DataView DV = new DataView(dt1);
//DV.RowFilter = "[P Date] IN (#11/01/2019#, #11/11/2019#)";
//DV.RowFilter = "[P Date] >=#"+dateTimePicker4.Text+"# and [P Date] <=#"+dateTimePicker5.Text+"#";
//dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values
//DV.RowFilter ="([P Date] >=CDate('dateTimePicker4.Text')) and ([P Date] <=CDate('dateTimePicker5.Text'))";
//DV.RowFilter = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "([P Date]>=#{dateTimePicker4.text}#) and ([P Date] <=#{dateTimePicker5.Text}#)");
dataGridView1.DataSource = DV;
For connection I am trying OLEDB connection.
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DatabasePath.accdb;
Jet OLEDB:Database Password=password";
connection.Close();
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
//Select all column use belw query
string query = "select * from Table1";
command1.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command1);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
this code is working but problem is that it shows all data not based on criteria based data.
I expect the output in Datagridview based on all criteria. Show only data which falls under all criteria.
I don't see you describing what's wrong with your results. If you are asking for a general help how to do it, here is one example. Bear in mind: The example is simple and does not use parametric query. That's up to you.
Converted C#
string wQueryCreated, wQueryChanged, wQueryCreatedBy, wQueryChandedBy;
if (this.fiCreated.Checked == true)
wQueryCreated = " AND DateCreated >= '" + Format(this.dtpFiCreatedOd.Value, "yyyy-MM-dd 00:00") + "' AND DateCreated <= '" + Format(this.dtpFiCreatedDo.Value, "yyyy-MM-dd 23:59") + " ' ";
else
wQueryCreated = "";
if (this.fiChanged.Checked == true)
wQueryChanged = " AND DateModified BETWEEN '" + Format(this.dtpDateChangedFrom.Value, "yyyy-MM-dd") + "' AND '" + Format(this.dtpDateChangedTo.Value, "yyyy-MM-dd") + "' ";
else
wQueryChanged = "";
if (this.fiCreatedBy.Checked == true)
wQueryCreatedBy = " AND PersonCreatedBy = " + this.fiCreatedBy.SelectedValue + " ";
else
wQueryCreatedBy = "";
if (this.fiChandedBy.Checked == true)
wQueryChandedBy = " AND PersonModifiedBy = " + this.fiChandedBy.SelectedValue + " ";
else
wQueryChandedBy = "";
// use query conditions in SELECT statement
queryString = "SELECT * FROM Table1 WHERE DateDeleted IS NULL " + wQueryCreated + wQueryChanged + wQueryCreatedBy + wQueryChandedBy + "; ";
Original VB.NET:
Dim wQueryCreated, wQueryChanged, wQueryCreatedBy, wQueryChandedBy As String
If Me.fiCreated.Checked = True Then ' filter date created
wQueryCreated = " AND DateCreated >= '" & Format(Me.dtpFiCreatedOd.Value, "yyyy-MM-dd 00:00") & "' AND DateCreated <= '" & Format(Me.dtpFiCreatedDo.Value, "yyyy-MM-dd 23:59") & " ' "
else
wQueryCreated = ""
End If
If Me.fiChanged.Checked = True Then ' filter datechanged
wQueryChanged = " AND DateModified BETWEEN '" & Format(Me.dtpDateChangedFrom.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.dtpDateChangedTo.Value, "yyyy-MM-dd") & "' "
else
wQueryChanged = ""
End If
If Me.fiCreatedBy.Checked = True Then ' filter chandged by person
wQueryCreatedBy = " AND PersonCreatedBy = " & Me.fiCreatedBy.SelectedValue & " "
else
wQueryCreatedBy = ""
End If
If Me.fiChandedBy.Checked = True Then ' filter modified by person
wQueryChandedBy = " AND PersonModifiedBy = " & Me.fiChandedBy.SelectedValue & " "
else
wQueryChandedBy = ""
End If
' use query conditions in SELECT statement
queryString = "SELECT * FROM Table1 WHERE DateDeleted IS NULL " & wQueryCreated & wQueryChanged & wQueryCreatedBy & wQueryChandedBy & "; "
This examples uses 4 conditions, taking information from 6 fields in total (dtp prefixes mean DateTimePicker). Notice a bit different date handling between first and second condition, which do similar thing.
Also notice, that this method requires 1 fixed condition. It could be 1=1, but obvously you usually use it like I did in the example, so i.e. to exclude soft-deleted rows (DateDeleted IS NULL). You need 1 fixed condition so that you don't have to care about the beginning " AND " in the rest of the conditions, regardless of their usage.
You can use "endless" conditions and combine them, even of a different data types. If you need to restrict to combination of conditions, validate they are filled in before you run the query. Obviously, you don't have to test for checked CheckBoxes, you can check for ComboBox1.SelectedValue > -1 (something is selected in ComboBox), or TextBox1.Text.Length >= 3 (at least 3 characters are entered into a TextBox), etc.
Hello Everyone I got a little confuse about selecting multiple fields from different tables binding it in one result, for you to understand it well, i posted my code & ERD below. thank you for your response. Please tell me where did I go wrong tnx :)
Here's the ERD of Mine:
and Here's the Code:
try
{
OleDbConnection Con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;");
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
Con.Open();
command.CommandText = String.Format("SELECT fn.Customer + ' ' + mi.Customer + ' ' + ln.Customer as [CUSTOMER FULLNAME], fn.Cashier + ' ' + mi.Cashier + ' ' + ln.Cashier as [CASHIER FULLNAME], prodName.Product as [PRODUCT NAME], prodDescription.Product as [PRODUCT DESCRIPTION], prodBrand.Product as [PRODUCT BRAND], prodQuantity.Transaction as [PRODUCT QUANTITY], prodTotalPrice.Transaction as [SUBTOTAL], job.Personnel as [Referral] FROM Product , [Order] , [Transaction] , Customer , Cashier , Personnel WHERE prodCode.Product = ProdCode.Order AND orderNo.Order = orderNo.Transaction AND pID.Personnel = pID.Transaction AND custID.Customer = custID.Transaction AND userID.Cashier = userID.Transaction AND sDate.Transaction = '{0}'", strDate);
command.Connection = Con;
adapter.SelectCommand = command;
adapter.Fill(dt);
Con.Close();
Con.Dispose();
gridViewTransac_1.DataSource = dt;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
Additional information: No value given for one or more required parameters.
I'm not a good sql query builder but shouldn't it be TableName.FieldName not the other way around ?
Anyways try to put the TableName first:
SELECT Customer.fn + ' ' + customer.mi + ' ' + customer.ln as [CUSTOMER FULLNAME]
, Cashier.f. + ' ' + Cashier.mi + ' ' + customer.ln as [CASHIER FULLNAME]
, Product.prodName as [PRODUCT NAME]
, Product.prodDescription as [PRODUCT DESCRIPTION]
, Product.prodBrand as [PRODUCT BRAND]
, Transaction.prodQuantity as [PRODUCT QUANTITY]
, Transaction.prodTotalPrice as [SUBTOTAL]
, Personnel.job. as [Referral]
FROM Product
, [Order]
, [Transaction]
, Customer
, Cashier
, Personnel
WHERE Product.prodCode = Order.ProdCode
AND Order.orderNo = Transaction.orderNo
AND Personnel.pID= Transaction.pID
AND Customer.custID = Transaction.custID
AND Cashier.userID = Transaction.userID
AND Transaction.sDate = #transDate
For #transDate you should add:
command.Parameters.AddWithValue("#transDate", someDate);
or you could simply do as you did
i need show multi checkbox on datagridview.
i have 4 checkbox when select 2 checkbox it's show 2 checkbox on datagridview.
Ex 2 checkbox.
CheckBox missShw
0001
0002
CheckBox leaveFull
0003
0004
i'm First select CheckBox missShw and CheckBox leaveFull it's output.
0003
0004
OR
i'm First select CheckBox leaveFull and CheckBox missShw it's output.
0001
0002
i need output when 2 checkbox.
0001
0002
0003
0004
now, i'm select 2 checkbox, so it's show all data to datagridview but it's don't show all data.
This code:
public void missShw()
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].Title + ' ' + [Employee].[First Name] + ' ' + [Employee].[Last Name] as 'FullName',[filesTA].ChkDate"
+ ",Convert(nvarchar(5),[filesTA].ChkIn,108) as 'ChkIn',Convert(nvarchar(5),[filesTA].ChkOut,108) as 'ChkOut"
+ ",[filesTA].LateMin"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ChkDate ='" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "'"
+ " and [Employee].Section = '" + cbSection.SelectedValue + "'"
+ " and [Employee].Team = '" + cbTeam.SelectedValue + "'"
+ " and [filesTA].ErrorCode = '2'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
public void leaveFull()
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].Title + ' ' + [Employee].[First Name] + ' ' + [Employee].[Last Name] as 'FullName',[filesTA].ChkDate"
+ ",Convert(nvarchar(5),[filesTA].ChkIn,108) as 'ChkIn',Convert(nvarchar(5),[filesTA].ChkOut,108) as 'ChkOut"
+ ",[filesTA].LateMin"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ChkDate ='" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "'"
+ " and [Employee].Section = '" + cbSection.SelectedValue + "'"
+ " and [Employee].Team = '" + cbTeam.SelectedValue + "'"
+ " and [filesTA].ErrorCode = '3'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
//missShw()
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
if (checkBox4.Checked == true)
{
missShw();
}
}
//leaveFull()
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked == true)
{
leaveFull();
}
}
Thanks for your time. :)
i want to fix a grdview column width in page load event.
i bounded this gridview from c# and also uses a datasource from c#
i want to set width for "Address" column ,because it has long data.i also want to use auto scroll to this gridview .
here is my code...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("Select DISTINCT FName+ ' ' +MName+ ' ' +LName as Name,"
+ " HomePhone,MobileNo1,"
+ " UPPER(ResAddr1) ++' '+ UPPER(Resaddr2) ++' '+ UPPER(ResAddr3) ++' '+ UPPER(Resaddr4) ++' '+ UPPER(Resaddr5) ++' '+ UPPER(Resaddr6) ++' '+ Pincode ++' '+City as Address,"
+ " g.Category,f.GroupName as 'Group',Seats,"
+ " dbo.CONCATWTOTSHOW(d.MemberId,d.GID,d.CID)As SeatNo,"
+ " AmountExpected,AmountReceived,Discount,AmountPending,b.Remarks as Reference, (d.MemberId)"
+ " from Person_Master a INNER JOIN Member_Master b ON a.PersonId=b.PersonId"
+ " LEFT JOIN Payment_Master c ON b.MemberId = c.MemberId"
+ " INNER JOIN SeatAssign_Master d ON b.MemberId = d.MemberId"
+ " INNER JOIN Year_Master e ON b.Year = e.Id"
+ " INNER JOIN Group_Master f ON d.Gid=f.Gid"
+ " INNER JOIN Category_Master g ON d.Cid=g.Cid "
+ " where b.Year=2 and g.Cid=2 and b.Active=1 and d.Active=1 ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
so do it in RowCreated event
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Width = 200;
// GridView1.Columns[0].HeaderStyle.Width = 100;
}
One way is to create a Grid view RowCreated event and in that event write
e.Row.Cells[1].Width = Unit.Pixel(300);
Where [1] is the column index.
I have first manually created a DataSet in my project name recvd.xsd having corresponding recvd.xss. On my button click event i have done the following coding.
try
{
DataSet recvd_REPORT = new DataSet();
DataTable REPORT = new DataTable();
String dd_webCofig = ConfigurationManager.ConnectionStrings["server2"].ConnectionString;
OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig);
ddlistconn.Open();
REPORT = recvd_REPORT.Tables["REPORT"];
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = typeof(System.Int32);
myDataColumn.ColumnName = "RECEIVED";
myDataColumn.ReadOnly = false;
myDataColumn.Unique = false;
// Add the Column to the DataColumnCollection.
REPORT.Columns.Add(myDataColumn);
string query = "SELECT case_no as \"RECEIVED\" from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
Response.Write(query);
OdbcCommand cmd = new OdbcCommand(query, ddlistconn);
OdbcDataReader loginMyReader = cmd.ExecuteReader();
OdbcDataAdapter adptr = new OdbcDataAdapter(query, ddlistconn);
adptr.Fill(REPORT);
ddlistconn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
I am getting the error as
Object reference not set to an instance of an object.
If i remove as \"RECEIVED\" from my SQL query and simply execute my SQL query than the result of my query is as follows (varies depending on user input)
200200000452011 ......, n numbers of 12 digit number.
Please help me to remove the error as to why am i not able to bind to DataTable.
I am getting the error before Response.Write(query); is executed, why is that problem?
I removed the try catch block and now i get the error as
try
SELECT case_no as `RECEIVED` ...
or just
SELECT case_no as RECEIVED ...
Anyway the correct DataSet filling code should look like this:
DataSet ds = new DataSet();
using (OdbcConnection connection = new OdbcConnection(connectionString))
using (OdbcCommand command = new OdbcCommand(sqlQuery, connection)
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command)
{
adapter.Fill(ds);
}
In your SQL instead of \"RECIEVED\" have you tried just RECIEVED, no quotes?
You need not to use \"RECEIVED\" in the query, you can use like below.
query = "SELECT case_no as [RECIEVED] from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
you can write query as like
query = "SELECT case_no as RECIEVED from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
check like that....