1. I have query.But couldn't add second where condition.Please suggest me the correct semantic .
2. And how can fetch the data from dropdownlist and show it in gridview.
3. How can i fetch value from Tution fee Column of my database when condition satisfies ,and Hostel Fee on fail of condition.??
protected void BindGridview()
{
constr = ConfigurationManager.ConnectionStrings["connstring_DETMIS"].ToString(); // connection string
// String FID = DropDownList1.SelectedItem.Value;
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(constr)) {
conn.Open();
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" + " where F_id =" + DropDownList1.SelectedItem.Value " and C_id=" + DropDownList2.SelectedItem.Value, conn)) {
using (var reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
gvDetails.DataSource = reader;
gvDetails.DataBind();
} else
lblWarning.Text = "There are no records..";
}
}
}
}
Welcome to Stackoverflow. You should first research on the google as why you are not able to add multiple conditions(It's just because of simple syntax mistake).
The exact code of line would be something like this.
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" +
" where F_id = '" + DropDownList1.SelectedItem.Value + "' and C_id=" + DropDownList2.SelectedItem.Value + "'", conn))
NOTE:- As a fellow developer, I won't suggest you to do this by passing values from here as it is dangerous and prone to SQL INJECTION
I would rather tell you to go by using Parameterized queries
Hope that helps and for future go for the Parametrized ones, as it is easy and technically preffered.
protected void BindGridview()
{
String strConnString = ConfigurationManager
.ConnectionStrings["connstring_DETMIS"].ConnectionString;
String strQuery = "select * from student_details " +
"where F_id=#F_Id and C_id=#C_Id";
MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(strConnString);
MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Parameters.AddWithValue("#F_Id",
DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#C_Id",
DropDownList2.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
Related
this is in my controller
string connStr = "server=" + IpAddress + ";user=" + UserName + ";database=" + DatabaseName + ";port=" + PortNumber + ";password=" + Password + ";SslMode=none;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = " select * from Cities,Regions";
MySqlCommand com = new MySqlCommand(query, conn);
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
I use a view model for displaying data from mysql and i fill them as below.
List<Models.ViewModels.city> CT = new List<Models.ViewModels.city>();
SftpClient sftpclient = new SftpClient("port", "root", "name");
sftpclient.Connect();
foreach (DataRow item in ds.Rows)
{
city ct = new city
{
CityName = item.itemArray[1].ToString(),
CityNumber = Convert.ToInt32(item.itemArray[2])
}
region rg = new region
{
RegionName = item.itemArray[1].ToString(),
RegionNumber = Convert.ToInt32(item.itemArray[2])
}
}
CT.Add(ct);
return View(CT.ToList());
How could i show regions in my razor. i already used viewbag for sending a list form my region viewmodel. but it doesn't fill the viewmodel obviously but how should i fill the region viewmodel
I am writing code in asp.net. I have a column named c_name in database. I want to store all my columns values in an array. Here is my incomplete code. I am confused what to do here.
String str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
cmd.ExecuteNonQuery();
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (mdr.Read())
{
}
Please help.
Check below code:
String str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
List<string> list = new List<string>();
while (mdr.Read())
{
list.Add(mdr.GetString(0));
}
string[] strMyArray = list.ToArray<string>();
I suspect one of your your problems is this line:
cmd.ExecuteNonQuery();
You're actually executing cmd twice, once with this line and once again when you create your reader. I've also added a little code to copy the result into an element in a list. Try the following:
string str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// create a list to hold the results in
List<string> results = new List<string>();
while (mdr.Read())
{
// for each row read a string and add it in
results.Add(mdr.GetString(0));
}
You've asked for an array - I've used a list because it's easier. If you REALLY want an array then just call:
var theArray = results.ToArray();
I would also suggest throwing in some using blocks around the connection, command and reader.
i am developing a website and i want to register the school children in a bulk way as they will provide the excel sheet and want that when i upload that sheet it automatically register user in userinfo table
here is the code
if (Request.Files["FileUpload1"] != null && Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224446;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Planetskool-20130901224446.mdf;Database=DefaultConnection; Trusted_Connection=true;Persist Security Info=True";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [UserInfoID],[UserID],[GraphID],[UserLevelEnumId],[Title],[FirstName],[MiddleName],[LastName],[Birthdate],[Gender],[Email],[MobileNo],[Country],[Zipcode],[CountFollowers],[CountFollows],[CountFiles],[CountPhotos],[Quote],[AvatarURL],[isVerified],[VerificationCount],[UserEnumType],[UserCreatorId] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "UserInfo";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
your code like below
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there.
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
Debug.Write("SheetTitle = " + excelSheets[t]);
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
DataSet ds = new DataSet();
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
}
}
for (int i = 0; i < myClass.Length; i++)
{
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
cmdB.Parameters.AddWithValue("#EngPosFT", Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters.AddWithValue("#RegNumber", myClass.GetValue(i));
cmdB.Parameters.AddWithValue("#EngFTAv", Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", drpClass.SelectedValue);
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
assuming myClass.Length is 60. This does 60 update statements. How can I limit it to 1 update statement. Please code example using the above code will be appreciated. Thanks
Tried using this
StringBuilder command = new StringBuilder();
SqlCommand cmdB = null;
for (int i = 0; i < myClass.Length; i++)
{
command.Append("UPDATE CumulativeTable SET" + " EngPosFT = " + Convert.ToInt32(Pos.GetValue(i)) + "," + " EngFTAv = " + Math.Round((engtot / arrayCount), 2) +
" WHERE RegNumber = " + myClass.GetValue(i) + " AND Session= " + drpSess.SelectedValue + " AND Form= " + drpForm.SelectedValue + " AND Class= " + drpClass.SelectedValue + ";");
//or command.AppendFormat("UPDATE CumulativeTable SET EngPosFT = {0},EngFTAv={1} WHERE RegNumber ={2} AND Session={3} AND Form={4} AND Class={5};", Convert.ToInt32(Pos.GetValue(i)), Math.Round((engtot / arrayCount), 2), myClass.GetValue(i), drpSess.SelectedValue, drpForm.SelectedValue, drpClass.SelectedValue);
}//max length is 128 error is encountered
Look at the BULK INSERT T-SQL command. But since I don't have a lot of personal experience with that command, I do see some immediate opportunity to improve this code using the same sql by creating the command and parameters outside of the loop, and only making the necessary changes inside the loop:
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
//I had to guess at the sql types you used here.
//Adjust this to match your actual column data types
cmdB.Parameters.Add("#EngPosFT", SqlDbType.Int);
cmdB.Parameters.Add("#RegNumber", SqlDbType.Int);
//It's really better to use explicit types here, too.
//I'll just update the first parameter as an example of how it looks:
cmdB.Parameters.Add("#EngFTAv", SqlDbType.Decimal).Value = Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", SqlDbTypedrpClass.SelectedValue);
for (int i = 0; i < myClass.Length; i++)
{
cmdB.Parameters[0].Value = Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters[1].Value = myClass.GetValue(i));
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
It would be better in this case to create a stored procedure that accepts a Table Valued Parameter. On the .NET side of things, you create a DataTable object containing a row for each set of values you want to use.
On the SQL Server side of things, you can treat the parameter as another table in a query. So inside the stored proc, you'd have:
UPDATE a
SET
EngPosFT = b.EngPosFT,
EngFTAv=b.EngFTAv
FROM
CumulativeTable a
inner join
#MyParm b
on
a.RegNumber =b.RegNumber AND
a.Session=b.Session AND
a.Form=b.Form AND
a.Class=b.Class
Where #MyParm is your table valued parameter.
This will then be processed as a single round-trip to the server.
In such scenarios it is always best to write a Stored Procedure and call that stored proc in the for loop, passing the necessary arguments at each call.
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataTableExample
{
class Program
{
static void Main(string[] args)
{
DataTable prodSalesData = new DataTable("ProductSalesData");
// Create Column 1: SaleDate
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "SaleDate";
// Create Column 2: ProductName
DataColumn productNameColumn = new DataColumn();
productNameColumn.ColumnName = "ProductName";
// Create Column 3: TotalSales
DataColumn totalSalesColumn = new DataColumn();
totalSalesColumn.DataType = Type.GetType("System.Int32");
totalSalesColumn.ColumnName = "TotalSales";
// Add the columns to the ProductSalesData DataTable
prodSalesData.Columns.Add(dateColumn);
prodSalesData.Columns.Add(productNameColumn);
prodSalesData.Columns.Add(totalSalesColumn);
// Let's populate the datatable with our stats.
// You can add as many rows as you want here!
// Create a new row
DataRow dailyProductSalesRow = prodSalesData.NewRow();
dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
dailyProductSalesRow["ProductName"] = "Nike";
dailyProductSalesRow["TotalSales"] = 10;
// Add the row to the ProductSalesData DataTable
prodSalesData.Rows.Add(dailyProductSalesRow);
// Copy the DataTable to SQL Server using SqlBulkCopy
using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = prodSalesData.TableName;
foreach (var column in prodSalesData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(prodSalesData);
}
}
}
}
}
I've posted several questions regarding this but none of them really helped me... Here I go with a clearer explanation:
I put data into the SQL table, here is what type of data goes in (All of them are String type):
http://i40.tinypic.com/33kaoat.png
When I click "Submit" button - the data saves in the table when I check it from PhpMyAdmin. But now I want to retrieve this data into this next tab form when I click "Refresh" button: http://i41.tinypic.com/34hdtv4.png
textBox5 is the textbox which I want my data to show up after I click on "Refresh" button
Here is the script I've done so far for the "Refresh" Button, but it gives me an error:
private void button3_Click(object sender, EventArgs e)
{
string connString = "Server=localhost;Database=request;Uid=root;Pwd=;";
using (MySqlConnection mcon = new MySqlConnection(connString))
using (MySqlCommand cmd = mcon.CreateCommand())
{
mcon.Open();
cmd.CommandText = "SELECT * FROM requesttcw";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
this.textBox5.Text = reader.GetString("UPDATE `requesttcw` SET `ID`=[value-1]");
this.textBox5.Text = " || ";
this.textBox5.Text = reader.GetString("UPDATE `requesttcw` SET `ClanName`=[value-2]");
this.textBox5.Text = " || ";
this.textBox5.Text = reader.GetString("UPDATE `requesttcw` SET `Date`=[value-3]");
this.textBox5.Text = " || ";
this.textBox5.Text = reader.GetString("UPDATE `requesttcw` SET `Type`=[value-4]");
this.textBox5.Text = " || ";
this.textBox5.Text = reader.GetString("UPDATE `requesttcw` SET `Rules`=[value-5]");
this.textBox5.Text = " || ";
}
reader.Close();
}
mcon.Close();
}
}
The textbox I want the data to showin is called textBox5.
Why can't you use a ListBox instead to show the string?
ListBox.Items.Add(<Your DataReader String>);
Edited
I assume that you are updating the table once and than you want to pick the updated row and show the items. If this is the case, update the table as:
UPDATE requesttcw SET
ID=value-1,
ClanName = Value-2,
Date = value-3,
Type = value-4,
Rules = value-5
After that, run your select query and initialize the DataReader. With DataReader:
string StringToShow = dr[0] + "||" + dr[1] .....
textBox5.Text = StringToShow;
Here I am assuming that you are picking a single row. If you want to continuously pick rows and keep showing, then you need to use ListBox.