how change result - c#

I try to create messeneger for my company where We have DNS (every pc has static ip and name of PC). All works by insert,select(mysql). I want to send group message where I choose name of PC and IP address
here is code for computer information
{
IPHostEntry he;
string myip = "";
he = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in he.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
myip = ip.ToString();
}
}
label1.Text = myip;
}
string pc = System.Environment.MachineName;
here I want to select group (skupina) of computers and insert to the messages (nrp)
using (MySqlConnection cnn = new MySqlConnection("Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;"))
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT namepc FROM skupina where nazovskup= 'mojask' ", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "skupina");
List<string> skName = new List<string>();
foreach (DataRow row in ds.Tables["skupina"].Rows)
{
skName.Add(row["namepc"].ToString());
string constring = "Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;";
var Query = "INSERT INTO OitDB.skup(uzivatel)VALUES(#name)";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
cmdDatabase.Parameters.Add("#name", MySqlDbType.VarChar).Value = string.Join("",skName.ToArray());
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Správa odoslaná!");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
but now I have result in mysql like:
row1-message1-pc1
row2-message1-pc1,pc2
row3-message1-pc1,pc2,pc3
and I want to:
row1-message1-pc1
row2-message1-pc2
row3-message1-pc3
Have you any idea?

this is functional code
using (MySqlConnection cnn = new MySqlConnection("Server=;Database=OitDB;Uid=martin;Pwd=;"))
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT namepc FROM skupina where nazovskup= 'mojask' ", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "skupina");
List<string> skName = new List<string>();
foreach (DataRow row in ds.Tables["skupina"].Rows)
{
skName.Add(row["namepc"].ToString());
string constring = "Server=;Database=OitDB;Uid=martin;Pwd=;";
var Query = "INSERT INTO OitDB.nrp(id,pc,ip,komu,datum,predmet,sprava,skupina)VALUES(#id,#pc,#ip,#komu,#cas,#predmet,#sprava,#name)";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
cmdDatabase.Parameters.AddWithValue("#id", idtxt.Text);
cmdDatabase.Parameters.AddWithValue("#pc", pc);
cmdDatabase.Parameters.AddWithValue("#ip", label1.Text);
cmdDatabase.Parameters.AddWithValue("#komu", comboBox1.Text);
cmdDatabase.Parameters.AddWithValue("#cas", cas);
cmdDatabase.Parameters.AddWithValue("#predmet", textBox1.Text);
cmdDatabase.Parameters.AddWithValue("#sprava", pisat.Text);
cmdDatabase.Parameters.Add("#name", MySqlDbType.VarChar).Value = row["namepc"];
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Správa odoslaná!");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

dropdownlist is not showing the selecteditem from the database

am trying to get the selected item from the database, but its not displaying nothing
code behind:
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("select id, message from Dropdown", connection);
SqlDataReader reader = cmd.ExecuteReader();
reader.Close();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
code of buttonclick
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string selectCommand = "Insert into Register (name,designation,company,mobile,email,message) values(#name,#designation,#company,#mobile,#email,#message);";
SqlCommand cmd = new SqlCommand(selectCommand, connection);
cmd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cmd.Parameters.AddWithValue("#designation", txtdesignation.Text.Trim());
cmd.Parameters.AddWithValue("#company", txtcompany.Text.Trim());
cmd.Parameters.AddWithValue("#mobile", txtmobile.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
cmd.Parameters.AddWithValue("#message", DdlRegister.SelectedItem.Text.Trim());
int cnt = cmd.ExecuteNonQuery();
if (cnt > 0)
{
ShowMessage("Registeration is done");
}
Response.Redirect("Index.aspx");
connection.Close();
}
catch (Exception ex)
{
}
design
<asp:DropDownList ID="DdlRegister" runat="server" CssClass="form-control ddl " OnSelectedIndexChanged="DdlRegister_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
try something like this
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[sortcompany]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
Company.ValueMember = "company_name";
Company.DisplayMember = "company_name";
Company.DataSource = dt;

Empty rows when retrieving data from database to dataGridView in c#

Why do I get blank rows when I retrieve rows from MySQL database to dataGridView? I end up getting the amount of rows but its empty (it has no text).
this is my code so far:
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I tried below code sample to get data from database and bind to datagridview.
var ConnectionString = "your ConnectionString";
MySqlConnection connect = new MySqlConnection(ConnectionString);
MySqlCommand cmd = new MySqlCommand("your query");
connect.Open();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = new DataTable();
dt = DtSet.Tables[0];
dataGridView1.DataSource = DtSet.Tables[0];
connect.Close();
Try This:
private void BindGrid()
{
string conString = #"Data Source=localhost;port=3306;Initial Catalog=TopShineDB;User Id=root;password=0159";
using (MySqlConnection con = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Table1", con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
*Just Clear your Columns you define in DataGridView *
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Columns.Clear();
dataGridView1.DataSource = bs;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
c#

how to display data from multiple tables to dataGridView

I want to display the phonebook and email data in one dataGridView. and the problem is it will only display the email table
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM phonebook";
cmd.CommandText = "SELECT * FROM email";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Clone();
}
}
you need to join two tables and fetch the results as below
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT pb.Id, pb.Name, pb.MobileNo, e.email FROM phonebook pb INNER JOIN email e ON e.Id= pb.Id";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}

How to display images from mysqldatabase using c# in WPF?

string constring = "server=localhost;uid=root;" + "pwd=12345;database=products;";
string query = "SELECT prd_items_image FROM products.prd_items where prd_items_id=5";
MySqlConnection condatabase = new MySqlConnection(constring);
MySqlCommand cmddatabase = new MySqlCommand(query, condatabase);
MySqlDataReader myreader;
try
{
condatabase.Open();
myreader = cmddatabase.ExecuteReader();
while (myreader.Read())
{
byte[] imgg = (byte[])(myreader["prd_items_image"]);
if (imgg == null)
box.Image = null;
else
{
MemoryStream mstream = new MemoryStream(imgg);
box.Image = System.Drawing.Image.FromStream(mstream);
}
}
I am getting error at if condition,
box.Image=null andbox.Image = System.Drawing.Image.FromStream(mstream);
In these two cases, I am getting error at Image.
So please check it once. If you have any other code ,provide me if required.

SQL Server connection in WPF

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Categories

Resources