Set first column of table as link - c#

I am loading my table from mysql and I want to make first column link. I mean link to another form. I want to display student details and when click on a name program will open a new form and display all info about student. Anyone have any idea about how to do?
DataTable table = new DataTable();
MySqlDataAdapter adapsql = new MySqlDataAdapter("SELECT name, surname, dob, sex, nationality, mobile, notes FROM student", connection);
adapsql.Fill(table);
dataGridView1.DataSource = table;
int x = (dataGridView1.RowCount)-1;
label21.Text = Convert.ToString(x);
cmd = connection.CreateCommand();
cmd.CommandText = #"SELECT * FROM reservation";
MySqlDataReader Reader = cmd.ExecuteReader();
if (!Reader.HasRows) return;
while (Reader.Read())
{
reservation.Add(Convert.ToInt16(GetDBString("roomID", Reader)));
}
Reader.Close();

You can handle this under the following event:
dataGridView1_CellClick
Get the CurrentCell value of the datagridiview and use this information to open your second form and add the required information to the fields you have there.
Sample code:
if (this.dataGridView1.CurrentCell != null)
{
string valueofcell=dataGridView1.CurrentCell.Value.ToString();
// Raise the corresponding form as per you required
}

Related

DropDownList always delete the first value?

i'm creating a recipe website for meals. I make an admin panel and i want to delete a meal which i added before. And there is a menu which includes number of the meal. For example there are 4 meals in pasta category and it shows Pasta(4) at mainpage.
Me as an admin, if i would like to add a new meal to my website, it's working. I select a category and it's adding to that category. But for deleting, it's working wrong. It always delete the first value in DropDownList which is Meat Foods. Can you help me to find an answer?
Here is the code:
if (Page.IsPostBack == false)
{
id = Request.QueryString["YemekId"];
islem = Request.QueryString["islem"];
SqlCommand komut2 = new SqlCommand("Select *from Kategoriler", baglan.baglanti());
SqlDataReader oku2 = komut2.ExecuteReader();
DropDownList1.DataTextField = "KategoriAd"; //DropDownList'e kategorilerin adlarını text biçiminde oldukları için bu şekilde çektik.
DropDownList1.DataValueField = "KategoriId"; //DropDownList'e kategorilerin id nolarını value değerinde oldukları için bu şekilde çektik.
DropDownList1.DataSource = oku2;
DropDownList1.DataBind();
SqlCommand komut = new SqlCommand("Select *from Yemek", baglan.baglanti());
SqlDataReader oku = komut.ExecuteReader();
DataList1.DataSource = oku;
DataList1.DataBind();
}
//silme işlemi
if (islem == "sil")
{
SqlCommand komutsilme = new SqlCommand("Delete from Yemek where YemekId=#s1", baglan.baglanti());
komutsilme.Parameters.AddWithValue("#s1", id);
komutsilme.ExecuteNonQuery();
baglan.baglanti().Close();
SqlCommand kategorisil = new SqlCommand("Update Kategoriler set KategoriAdet=KategoriAdet-1 where KategoriId=#k1", baglan.baglanti());
kategorisil.Parameters.AddWithValue("#k1", DropDownList1.SelectedValue);
kategorisil.ExecuteNonQuery();
baglan.baglanti().Close();
Response.Write("<script> alert('Yemek başarıyla silindi!')</script>");
}
you are passing a id as a string from your query string to the parameter
komutsilme.Parameters.AddWithValue("#s1", id);
I am assuming YemekId is an int in your database so try this
komutsilme.Parameters.AddWithValue("#s1", int.Parse(id));
AddWithValue will derive the type of the parameter of its value, so ensure that it's the correct type, in this case int not string.

C#: how to add 2 values in ComboBox from stored procedure

I have TWO questions, first how to add 2 values and second is: if we add 2 values so we need to change the code when we save combo-box value in database (second question with code I also ask from end of this question)?
I need to add 2 values from table dep_Id and dep_Name in `ComboBox; like this:
(Department ID: Department Name)
This is the stored procedure:
CREATE PROCEDURE [dbo]. SelectComoboxData_SP
AS
SELECT dep_Id, dep_Name
FROM department
RETURN 0
This is the C# code:
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
com_boxDepartment.Items.Add(dr["dep_Id"]);
com_boxDepartment.SelectedIndex = 0;
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("<<<INVALID SQL OPERATION \n" + ex);
}
con.Close();
}
Let me also know when I select any department from the combobox so now I wrote this code
cmd.Parameters.AddWithValue("#dId", com_boxDepartment.Text);
for saving by id, so when add 2 values in combobox so we need to change anything?
If it were my C# I'd do it more like this (though I'd use strongly typed datasets)
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
com_boxDepartment.DataSource = dt;
com_boxDepartment.DisplayMember = "dep_Name";
com_boxDepartment.ValueMember = "dep_Id";
}
Your combo will show "History Department" for example, but when you ask it for the .SelectedValue it will return e.g. 2 (the id for the history department)

if the content in the label matches a cell in a row C#

If the content in the label matches a cell content in 'column1' (the order ID column) of the database (similar concept to a login form), change value of cell 4 (the order location) in that specific row (and only that row) to specific value in textbox
if (result == DialogResult.Yes) // When the button is clicked and the user selects yes.
{
OleDbDataAdapter da = new OleDbDataAdapter("Select * from [Customer Orders] WHERE [Order ID] = #OrderId", MAcon);
da.SelectCommand.Parameters.AddWithValue("#OrderId", OleDbType.Integer);
// da.SelectCommand.Parameters.Add("#OrderId", OleDbType.Integer).Value = 2;
DataTable dtbl = new DataTable();
da.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
OleDbCommand cmd = new OleDbCommand("UPDATE [Customer Orders] SET [OrderStatus] = (#OrderStatus), [OrderID]= #OrderId", MAcon); //SET[Order Status] = (#OrderStatus)
MAcon.Open();
cmd.Parameters.AddWithValue("#OrderID", orderID);
cmd.Parameters.AddWithValue("#OrderStatus", Location.Text);
cmd.ExecuteNonQuery();
MAcon.Close();
MessageBox.Show("Production has begun");
}
could someone help me as of now, every cell in column 4 changes and I'm not sure what I've done wrong
This line:
OleDbCommand cmd = new OleDbCommand("UPDATE [Customer Orders] SET
[OrderStatus] = (#OrderStatus), [OrderID]= #OrderId", MAcon);
Needs a WHERE clause.
Based on your description in the question, possibly:
WHERE column1 = labelContent

C# Displaying a sql database object's name in a label.Text property on "SelectedIndexChanged" Event

I am trying to make a small contact book that takes contacts details from a mssql database.It has 3 tables: contacts, last_talk(last time i talked with a contact+short description of the discussion), and another table(that has both primary keys from the first 2 tables )
On the form(tab of tabcontrol) where i display the contacts, i have added 2 listboxes, one loads and displays the contacts names, and the second listbox loads the "Last talk" list for every contact i select depending how many "talks" i had with a contact.
What i am trying to do now is: when i select a contact, i also want to display near the listboxes, some labels for the contact name, company, etc, that change their text to the database entry for the selected contact's name/company...
Here is a part of the code:
private void lstContactList_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateTalkList();
PopulateContactLabels();
}
private void ContactBookForm_Load(object sender, EventArgs e)
{
PopulateContactList();
}
private void PopulateContactList()
{
string query = "SELECT * FROM Contact";
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
connection.Open();
DataTable contactTable = new DataTable();
adapter.Fill(contactTable);
lstContactList.DisplayMember = "Name";
lstContactList.ValueMember = "Id";
lstContactList.DataSource = contactTable;
}
}
here is the method that i try to use to change the labels:
private void PopulateContactLabels()
{
string query = "SELECT * FROM Contact";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
connection.Open();
SqlDataReader rdr = command.ExecuteReader();
while (rdr.Read())
{
lblContactName.Text = rdr["Name"].ToString();
lblCompany.Text = rdr["Company"].ToString();
lblOccupation.Text = rdr["Occupation"].ToString();
lblPhoneNumber.Text = rdr["PhoneNumber"].ToString();
lblEmail.Text = rdr["Email"].ToString();
}
rdr.Close();
connection.Close();
}
}
And it does change the labels, but it selects the last contact added to the database, and it doesn't change when i select another contact.
What am i doing wrong?
That's because in your PopulateContactLabels method, you are selecting the whole Contact table and then reading through the whole list, so it's always the last one which is shown.
You need a query more like SELECT * FROM Contact WHERE ContactId = #contactID, and then add the contactId (or whatever value you are using to find the contact) as a parameter on the SqlCommand object.

How to get the data when I select a datagridview cell or column

I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.

Categories