Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Visual C从SQL Server表中获取ID号_C#_Sql Server_Visual Studio - Fatal编程技术网

C# 如何使用Visual C从SQL Server表中获取ID号

C# 如何使用Visual C从SQL Server表中获取ID号,c#,sql-server,visual-studio,C#,Sql Server,Visual Studio,作为初学者,我一直在接受数据库和C编程概念的培训。我刚刚在SQLServer中创建了一个表,并在其中插入了一些图像文件 我还创建了一个表单项目,用于将图像保存到该DB表中,并检索以在picturebox中显示它们 我正在尝试获取ID号并加载到组合框中,以便选择相关图像的ID号。我设法将图像文件保存到DB,但无法将ID号检索到组合框中 我恳请你给我一个简单的解释和一些建议。你可以在下面查看我的代码 公共部分类Form1:Form { 公共表格1 { 初始化组件; } 私有无效按钮1\u单击对象发送

作为初学者,我一直在接受数据库和C编程概念的培训。我刚刚在SQLServer中创建了一个表,并在其中插入了一些图像文件

我还创建了一个表单项目,用于将图像保存到该DB表中,并检索以在picturebox中显示它们

我正在尝试获取ID号并加载到组合框中,以便选择相关图像的ID号。我设法将图像文件保存到DB,但无法将ID号检索到组合框中

我恳请你给我一个简单的解释和一些建议。你可以在下面查看我的代码

公共部分类Form1:Form { 公共表格1 { 初始化组件; } 私有无效按钮1\u单击对象发送者,事件参数e { SqlConnection con=新的SqlConnectionDBHandler.GetConnectionString; 尝试 { OpenFileDialog fop=新建OpenFileDialog; fop.InitialDirectory=@C:\; fop.Filter=[JPG,JPEG]|*.JPG; 如果fop.ShowDialog==DialogResult.OK { FileStream FS=newFileStream@fop.FileName,FileMode.Open,FileAccess.Read; 字节[]img=新字节[FS.Length]; FS.Readimg,0,Convert.ToInt32FS.Length; 如果con.State==ConnectionState.Closed 不公开; SqlCommand cmd=new-SqlCommandSaveImage,con; cmd.CommandType=CommandType.storedProcess; cmd.Parameters。Add@img,SqlDbType.Image.Value=img; cmd.ExecuteNonQuery; //loadImageId; MessageBox.ShowImage保存成功!!,信息,MessageBoxButtons.OK,MessageBoxIcon.Information; } 其他的 { MessageBox.show请选择要保存的图像!!,信息,MessageBox按钮。确定,MessageBox图标。信息; } } 捕获异常 { MessageBox.Showex.Message,异常,MessageBoxButtons.OK,MessageBoxIcon.Error; } 最后 { 如果con.State==ConnectionState.Open con.关闭; } } 私有无效按钮3\u单击对象发送者,事件参数e { SqlConnection con2=新的SqlConnectionDBHandler.GetConnectionString; SqlCommand cmd2=新的SqlCommandReadImage,con2; cmd2.CommandType=CommandType.StoredProcess; cmd2.2参数。Add@imgId,SqlDbType.Int.Value= Convert.ToInt32comboBox1.SelectedValue.ToString;//我不确定使用ReadImage过程从表中获取图像时此行是否正确。 SqlDataAdapter da=新的SqlDataAdapter; da.SelectCommand=cmd2; DataTable dt=新的DataTable; da.Filldt; dataGridView1.DataSource=dt; } private void button2\u Clickobject sender,EventArgs e//我在这个代码块中遇到了一个问题,我想: { SqlConnection con3=新的SqlConnectionDBHandler.GetConnectionString; SqlCommand cmd3=新的SqlCommandReadAllImageIDs,con3; cmd3.CommandType=CommandType.StoredProcess; SqlDataAdapter dc=新的SqlDataAdapter; dc.SelectCommand=cmd3; DataTable dtt=新的DataTable; dc.Filldtt; comboBox1.DataSource=dtt; //dataGridView1.DataSource=dtt; }
我认为你需要为你的计划设定你的和

在使用实现SqlConnection、SqlCommand、SqlDataAdapter的对象时,最好使用using块来确保正确处理它们。因此,您的方法可能会变成:

private void button2_Click(object sender, EventArgs e)
{
    var dtt = new DataTable();
    using (var con3 = new SqlConnection(DBHandler.GetConnectionString()))
    using (var cmd3 = new SqlCommand("ReadAllImageIDs", con3))
    {
        cmd3.CommandType = CommandType.StoredProcedure;

        using(var dc = new SqlDataAdapter())
        {
            dc.SelectCommand = cmd3;
            dc.Fill(dtt);
            comboBox1.DataSource = dtt;
            comboBox1.DisplayMember = "ID";
            comboBox1.ValueMember = "ID";
        }
    }
}
您还可以使用以select命令和连接字符串为参数的快捷方式,这样您就可以简化为:

private void button2_Click(object sender, EventArgs e)
{
    var dtt = new DataTable();

    using (var dc = new SqlDataAdapter("ReadAllImageIDs", DBHandler.GetConnectionString()))
    {
        dc.SelectCommand.CommandType = CommandType.StoredProcedure;
        dc.Fill(dtt);
    }
    comboBox1.DataSource = dtt;
    comboBox1.DisplayMember = "ID";
    comboBox1.ValueMember = "ID";
}
另请注意,将数据访问层DAL与UI分离通常是一个好主意。因此,您可能有一个单独的类,可能在单独的库中:

public class ImageService
{
    public static void SaveImage(string fileName)
    {
        byte[] img;
        using(var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        {
            img = new byte[fileStream.Length];
            fileStream.Read(img, 0, Convert.ToInt32(fileStream.Length));
        }
        using (var con = new SqlConnection(DBHandler.GetConnectionString()))
        using (var cmd = new SqlCommand("SaveImage", con))
        {
            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
            cmd.ExecuteNonQuery();
        }
    }
    public static DataTable GetAllImageIDs
    {
        var dtt = new DataTable();

        using (var dc = new SqlDataAdapter("ReadAllImageIDs", DBHandler.GetConnectionString()))
        {
            dc.SelectCommand.CommandType = CommandType.StoredProcedure;
            dc.Fill(dtt);
        }
        return dtt;
    }
}
然后,在您的UI中,您只需拥有:

private void button1_Click(object sender, EventArgs e)
{
     try
    {
        OpenFileDialog fop = new OpenFileDialog();
        fop.InitialDirectory = "C:\\";
        fop.Filter = "[JPG,JPEG]|*.jpg";

        if (fop.ShowDialog() == DialogResult.OK)
        {
            ImageService.SaveImage(fop.FileName);
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
private void button2_Click(object sender, EventArgs e)
{

    comboBox1.DataSource = ImageService.GetAllImageIDs();
    comboBox1.DisplayMember = "ID";
    comboBox1.ValueMember = "ID";
}

不太清楚您是否正在使用组合框或SQL

这应该给你一个良好的开端:

        List<string> ids = new List<string>();
        using (SqlConnection conn = new SqlConnection("MyConnectionString"))
        {
            using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", conn))
            {
                conn.Open();
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        ids.Add(rdr["NameOfIsField"].ToString());
                    }
                }
            }
        }

        MyListBox.DataSource = ids;
考虑:

存储过程返回的是什么 向用户显示ID是否有意义
抱歉-与@GarethDID同时键入将是我在表中的相关列名,对吗?是的,只需使用datatable中的列名来显示您想要显示的内容,以及您想要的值。我不确定您的过程返回了哪些列,因此不得不猜测。感谢您的回答。我的下一步将实现picturebox要显示图像:我也很感谢您的其他评论和安排。您是否使用FileName属性而不是FileName属性?您需要循环查看FileName中的每个文件名并保存每个文件名?如果您仍然卡住,我认为您可能需要用更新的代码问一个新问题。
        List<string> ids = new List<string>();
        using (SqlConnection conn = new SqlConnection("MyConnectionString"))
        {
            using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", conn))
            {
                conn.Open();
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        ids.Add(rdr["NameOfIsField"].ToString());
                    }
                }
            }
        }

        MyListBox.DataSource = ids;