连接C#和SQL Server 2008 R2 [英] connection c# and SQL server 2008 R2
本文介绍了连接C#和SQL Server 2008 R2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
请我有一个小问题,hier是我的代码.此代码遍历,但我不能给出多个数据(或信息).之后,我需要关闭WinForm并再次运行.问题出在哪儿?有人可以帮我吗.
Hey Every Body,
please Ihave a small problem, hier is my code. This code walk but i cannot give more than one data(or Informations). after that i need to close my WinForm and run it again. where is the Problem? can somed´body help me please.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Common;
namespace Netz_Vorgang
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection("Data Source=STEPHANE-YOTAT\\STEPHANE;Initial Catalog=DBtest;Trusted_Connection=Yes");
public Form1()
{
InitializeComponent();
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("error occured 2 " + ex.Message);
this.Dispose();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void _insert_Click(object sender, EventArgs e)
{
string com = string.Format("insert into Step values('{0}', '{1}')", (string)(_StepName.Text.ToString()), Int32.Parse(_Dauer.Text));
SqlCommand com2 = new SqlCommand(com,connection);
try
{
com2.ExecuteNonQuery();
connection.Dispose();
MessageBox.Show("successfull");
_StepName.Text.Equals( "");
_Dauer.Text = "";
_StepName.Focus();
this.Update();
}
catch (Exception ex)
{
MessageBox.Show("error occured 1" + ex.Message);
this.Dispose();
}
}
private void _show_Click(object sender, EventArgs e)
{
SqlCommand connec = new SqlCommand("select * from Table",connection);
DataSet vds = new DataSet();
SqlDataAdapter vda = new SqlDataAdapter(connec);
vda.Fill(vds,"ret");
dataGridView1.DataSource = vds.Tables["ret"];
connection.Dispose();
}
}
}
如果有人有其他解决方案,请妥善处理.感谢您的帮助.
Please if somebody have another Solution it wellcome. Thanks for ur Help.
推荐答案
不要在表单构造函数中进行connection.open操作.在进行任何操作之前先进行操作,然后确保将其关闭.
仅在窗体关闭时才设置连接,否则关闭连接应该没问题.
Dont do a connection.open in form constructor. do it before any operation and then make sure to close it.
Dispose the connection only when form closes else closing the connection should be fine.
在_show_Click
方法中,您要设置连接-onnection.Dispose();
.
从代码中删除该行.
In the_show_Click
method, you are disposing off your connection -onnection.Dispose();
.
Remove that line from your code.
谢谢.它走得很完美.
最好的问候.
thanks guy. it walk perfectly.
Best regards.
这篇关于连接C#和SQL Server 2008 R2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文