Retrieve Data from MySQL (phpmyadmin) to TextBox in visual c# - mysql

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.

Related

asp.net:query with multiple where conditions

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;
}
}

how to store columns values in array in asp.net

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.

Bulk Insert into SQL Server 2008

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);
}
}
}
}
}

Create SSRS subscriptions from web page

I have Reporting Services running on SQL 2008 R2 and have a handful of reports that I created. I'm able to go into Report Server and set up a subscription and have any of the reports emailed to an email address. So all of that is configured correctly.
What I want to do is have a web page in my application that shows a list of available reports. The user can choose one, choose a schedule frequency, enter an email address, and click a 'save' button. When clicking save it should create the subscription in SSRS. I may need to pass in a couple report parameters depending on the report.
How can I do this in C#?
You can dynamically generate a one time subscription in SSRS for the report. You'll have to use the RS webservice as mentioned by Diego.
Your code would look something like this:
static void generateSubscription()
{
if (SubscriptionRequests.Count < 1) return;
NetworkCredential credentials = new NetworkCredential("user", "pass");
reports.ReportingService2005 rs = new reports.ReportingService2005();
rs.Credentials = credentials;
DateTime topDatetime = DateTime.Now;
topDatetime = topDatetime.AddMinutes(2);
foreach (SubscriptionRequest x in SubscriptionRequests)
{
reports.ExtensionSettings extensionSettings = new reports.ExtensionSettings();
List<reports.ParameterValue> extParameters = new List<reports.ParameterValue>();
List<reports.ParameterValue> parameters = new List<reports.ParameterValue>();
string description = "Email: ";
string eventType = "TimedSubscription";
extensionSettings.Extension = "Report Server Email";
string scheduleXml = "<ScheduleDefinition><StartDateTime>";
scheduleXml += topDatetime.ToShortDateString() + " " + topDatetime.ToShortTimeString();
scheduleXml += "</StartDateTime></ScheduleDefinition>";
parameters.Add(new reports.ParameterValue() { Name = "abc", Value = x.id });
extParameters.Add(new reports.ParameterValue() { Name = "RenderFormat", Value = x.renderFormat });
extParameters.Add(new reports.ParameterValue() { Name = "TO", Value = x.email });
extParameters.Add(new reports.ParameterValue() { Name = "ReplyTo", Value = x.replyTo });
extParameters.Add(new reports.ParameterValue() { Name = "IncludeReport", Value = "True" });
extParameters.Add(new reports.ParameterValue() { Name = "Subject", Value = "subject - " + " (" + x.id.ToString() + ")" });
extParameters.Add(new reports.ParameterValue() { Name = "Comment", Value = x.body });
extensionSettings.ParameterValues = extParameters.ToArray();
description += topDatetime.ToShortDateString() + " " + topDatetime.ToShortTimeString();
description += " (" + x.a + " - " + x.b + " - " + x.c + ")";
string _reportName = "/report";
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
topDatetime = topDatetime.AddSeconds(30);
}
}
Easiest way is give access to the user to the report manager under the "Browser" pre-defined role. This is exactly what this role is about, view folders and reports and subscribe to reports.
If that's not possible you can create your own management tool. To do that you need to access the SSRS web methods Using SOAP and the ReportService2005 endpoint
Examples here

MS Exchange Web-Services: How to get items with 'Flag' set?

Does anyone know how to get all the items that are flagged inside the Inbox using Microsoft Exchange Web-Services?
Apparently they are neither inside Tasks folder (even though they appear there in Outlook), nor do they have IsReminderSet set to true.
Following attempts either return only appointments or true tasks only, but not flagged messages:
var msgsView = new ItemView(100);
var msgsFilter = new SearchFilter.IsEqualTo(ItemSchema.IsReminderSet, true);
var flagged = exSvc.FindItems(WellKnownFolderName.Inbox, msgsFilter, msgsView);
or
var taskView = new ItemView(100);
var tasks = exSvc.FindItems(WellKnownFolderName.Tasks, taskView);
neither work.
I know this question is old, but I just found list sample code which looks like it might do the trick (I haven't tested it myself yet)
source: http://independentsoft.de/exchangewebservices/tutorial/findmessageswithflag.html
IsEqualTo restriction1 = new IsEqualTo(MessagePropertyPath.FlagStatus, "1"); //FlagStatus.Complete
IsEqualTo restriction2 = new IsEqualTo(MessagePropertyPath.FlagStatus, "2"); //FlagStatus.Marked
Or restriction3 = new Or(restriction1, restriction2);
FindItemResponse response = service.FindItem(StandardFolder.Inbox
, MessagePropertyPath.AllPropertyPaths, restriction3);
for (int i = 0; i < response.Items.Count; i++)
{
if (response.Items[i] is Message)
{
Message message = (Message)response.Items[i];
Console.WriteLine("Subject = " + message.Subject);
Console.WriteLine("FlagStatus = " + message.FlagStatus);
Console.WriteLine("FlagIcon = " + message.FlagIcon);
Console.WriteLine("FlagCompleteTime = " + message.FlagCompleteTime);
Console.WriteLine("FlagRequest = " + message.FlagRequest);
Console.WriteLine("-----------------------------------------------");
}
}