Home > Enterprise >  How to find and display specific data in SQL Database with C# code in UWP app?
How to find and display specific data in SQL Database with C# code in UWP app?

Time:12-13

DISCLAIMER: I am complete beginner in using C# code for searching in SQL database, so I know practically nothing about this problem.

I was given a task to make a desktop app for searching a name of a product in a database based on its ID. The only thing I've successfully did was connecting the SQL database to the app via Visual Studio. On this picture you can see the clearest description I am able to give.

I have absolutely no clue what to even try. I've seen some class called SqlConnection, but again, I am not completely sure if it could help me somehow.

I am sure that this is one of the most basic problems ever posted on this site, but I am completely stuck and don't know what to do next.

Thanks for anything in advance.

EDIT: Yeah, I forgot to mention one pretty important thing - I am making this as UWP app. Sorry for that.

CodePudding user response:

Firstly you need to setup some connection for your database, Add this line to your web.config file

<connectionStrings>
  <add name="myDbConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

and then if you design UI Part, then call this function after button click on your UI,

protected void Button1_Click(object sender, EventArgs e)
    {
        //data soure control that works with sql database
        SqlDataSource sds = new SqlDataSource();
        //get connection string from application's web.config file
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();
        //create parameters with specified name and values
        sds.SelectParameters.Add("name", TypeCode.String, this.TextBox1.Text);
        //set the sql string to retrive data from the database
        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [name]=@name";
        //retrive data
        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
        if (dv.Count == 0)
        {
            this.Label1.Text = "No Data Found";
            return;
        }
        else
        {
            GridView1.DataSource = sds;
            GridView1.DataBind();
        }
    }

CodePudding user response:

For your scenario, please refer to Use a SQLite database in a UWP app document. It has detail steps to use Microsoft.Data.SQLite to load the database with specific table-command.

searching a name of a product in a database based on its ID.

SELECT * FROM [tb-name] WHERE [id]=@id"


selectCommand.Parameters.AddWithValue("@id", "id-value");
  • Related