C# LinkLabel to access database hyperlink - c#

I am trying to use a LInklabel to open a hyperlink i have on my access database. However, this is the first time using a linklabel. Any suggestions would be great!
con.Open();
str = "Select * from loc where link ='" + facility+ "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
linkLabel1.Text = dr.GetString(17);
}

The following code works for me:
private void Form1_Load(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, website FROM Clients WHERE ID = 1";
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
String fName = rdr["FirstName"].ToString();
String url = rdr["website"].ToString();
if (url.Substring(0,1).Equals("#"))
{
// remove leading and trailing hash marks from URL
// as retrieved from a Hyperlink field in Access
url = url.Substring(1, url.Length - 2);
}
linkLabel1.Text = String.Format("Link to {0}'s website", fName);
linkLabel1.Links.Add(0, linkLabel1.Text.Length, url);
}
con.Close();
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string target = e.Link.LinkData as string;
System.Diagnostics.Process.Start(target);
}

Related

How to add textbox data to a database?

I am making a school project and i need to put text input (name and gender) into a database. This database (the names and genders) then have to be shown in a listbox. The code i have at the moment is put below, how can i make it work? Thanks in advance!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
As i understand you just have to add a insert between button1.click and addToList process.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
Database Name : People
Table Name : Person
All Parts Image :

DropdownListSelectedValue to Label

I keep on getting the Name instead of the Price.What I want is I pick a value on The DropdownList and Load its price on the label.
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
while (rdr.Read())
{
lblPrice.Text = DropDownList1.SelectedValue.ToString();
}
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text=DropDownList1.SelectedItem.Value.ToString();
}
above is my selectedIndex.
Change your code into this:
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if(dr.HasRows)
{
while (rdr.Read())
{
lblPrice.Text = rdr.GetValue(0).ToString(); // if price is string use GetString(0))
}
}
connection.Close();
}
EDIT:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GetData();
}

C# ADO.NET: check for existing index

I have the following code and I want to show an error message if the id is not found in the table can any body help?
private void button4_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(cs);
string sql = "select * from question where id=#id;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
cmd.Prepare();
cmd.Parameters.AddWithValue("#id", int.Parse(textBox1.Text));
MySqlDataReader rd = cmd.ExecuteReader();
string res = "";
while (rd.Read())
{
if (rd.HasRows==true)
{
res = string.Format("id={0} pid={1} question={2}", rd.GetInt32(0), rd.GetInt32(1), rd.GetString(2));
MessageBox.Show("found" + "\n" + res);
}
MessageBox.Show(" id not found");
}
You need to check for has rows before to start iterating the reader.
if (rd.HasRows==true)
{
while (rd.Read())
{
// Do something here
}
}
else
{
// Show message here
}

How to display data from database into textbox, and update it

I can display my data in my textbox, dropdownlist after retrieve data from sql database, but when i proceed with my update button, the information edited in the textbox or dropdownlist wouldn't update into the database. I tried to remove the code in page load, and re-key in all the data manually, it can be update. All I want is retrieve data from database and display it in the textbox, and it can be update into the database after make some changes from the textbox. Can someone help me on this? Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UpdateCustomerDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE customer_registration SET password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno where username='" + Session["username"] + "'", con);
con.Open();
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text + DropDownListMonth.Text + DropDownListYear.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
}
Wrap your all statements in !IsPostBack condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
The answer is .IsPostBack as suggested by #Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load
private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}//end using
}
Then call it in your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateFields();
}
}
protected void Page_Load(object sender, EventArgs e)
{
DropDownTitle();
}
protected void DropDownTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Populate the text box values in the Page Init event as opposed to using the Postback.
protected void Page_Init(object sender, EventArgs e)
{
DropDownTitle();
}

Adding just Unique Data to Gridview

I have a table like this. Columns --> (MUSTERI, AVUKAT, HESAP (Unique))
My page design like this.
Simply, first dropdown is MUSTERI, second dropdown is AVUKAT, when i click EKLE (it means ADD) button, automaticyly getting HESAP (unique) and showing on gridview.
What i want is, if any user try to add a data which they are the same HESAP, geting an error.
For example;There is a data "2M LOJİSTİJ" "ALİ ORAL" "889" in my gridview.
Someone try to add a data like "2M LOJİSTİK" "EMRA SARINÇ" "889" showing an error and don't add to table.
My Add_Click button code is
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
And my first dropdown MUSTERI (getting HESAP auto by this field)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesapNo = DropDownList1.SelectedItem.Value;
string query = "select A.HESAP_NO from YAZ..MARDATA.S_TEKLIF A where A.MUS_K_ISIM = '" + hesapNo + "'";
SqlCommand cmd = new SqlCommand(query, myConnection);
if (DropDownList1.SelectedValue != "0")
{
Add.Enabled = true;
Label1.Text = cmd.ExecuteScalar().ToString();
}
else
{
Add.Enabled = false;
}
Label1.Visible = false;
myConnection.Close();
}
How can i blocking insert data which already have the same HESAP?
first check HESAP is exist or not in #AVUKAT then insert new entry.
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text.Trim();
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
string strsql= "SELECT * FROM AVUKAT WHERE HESAP = " + hesap;
SqlCommand com = new SqlCommand(strsql, myConnection);
SqlDataReader dread = com.ExecuteReader();
dread.read();
if(dread.HasRows)
{
myConnection.Close();
return;
}
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}

Categories

Resources