首页 \ 问答 \ 将Wpf的datagrid绑定到数据库(binding datagrid for Wpf to a DB)

将Wpf的datagrid绑定到数据库(binding datagrid for Wpf to a DB)

我试图将WPF的DataGrid绑定到MS SQL数据库中的表。

1)首先,我创建了一个App.config文件,如下所示

    <connectionStrings> 
      <add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress; 
       User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
    <connectionStrings/>

2)其次,我添加了一个名为grdEventLog的我的表单的数据网格

      <Grid>
        <DataGrid Name="grdEventLog"/>
      </Grid>

3)然后我将这段代码添加到MainWindow.xaml.cs文件中,如下所示:

     using System.Data;
     using System.Data.SqlClient;
     using System.Web;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        FillDataGrid();
    }

    private void FillDataGrid()
    {
        string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        string CmdString = string.Empty;
        using (SqlConnection con = new SqlConnection(ConString))
        {
            CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("EventLog");
            sda.Fill(dt);
            grdEventLog.ItemsSource = dt.DefaultView;
        }
    }

输入所有这些条目后,我在ConfigurationManager中出现错误,指出“名称在当前上下文中不存在”

我正在尝试添加参考cfgmgr32.dll来克服此错误。 但它没有被接受。 任何人都可以建议过来这个错误?!

也欢迎替代WPF中的数据绑定的替代建议。


I am trying bind a DataGrid for WPF to a table in MS SQL Database.

1) First I created a App.config file as followsrrr

    <connectionStrings> 
      <add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress; 
       User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
    <connectionStrings/>

2) Secondly, I added a datagrid to my Form with a name grdEventLog

      <Grid>
        <DataGrid Name="grdEventLog"/>
      </Grid>

3) then I added this code to MainWindow.xaml.cs file as follows:

     using System.Data;
     using System.Data.SqlClient;
     using System.Web;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        FillDataGrid();
    }

    private void FillDataGrid()
    {
        string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        string CmdString = string.Empty;
        using (SqlConnection con = new SqlConnection(ConString))
        {
            CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("EventLog");
            sda.Fill(dt);
            grdEventLog.ItemsSource = dt.DefaultView;
        }
    }

After typing all these entries, I have the error at ConfigurationManager stating "The name does not exist in the current context"

I am trying to add reference cfgmgr32.dll to overcome this error. But it is not being accepted. Can anyone suggest to over come this error ?!

Alternative suggestion for approaching databinding in WPF is also welcome.


原文:https://stackoverflow.com/questions/13685026
更新时间:2022-03-24 06:03

最满意答案

他们做不同的事情,所以你使用哪一个取决于你想要做什么。 第一个捕获try块中四行中任何匹配& except * except子句中的任何错误。 第二个版本每行“尝试”代码只捕获一种异常。 例如,如果从行entity1 = Entity1.objects.get(id=1) ,则第一个版本将捕获entity1 = Entity1.objects.get(id=1) ; 第二个版本不会捕获这样的错误,因为except KeyError该行的except KeyError子句except KeyError没有。

也就是说,一般来说,保持try block short是个好主意。 如果您要为第一行处理的唯一错误是Entity1.DoesNotExist ,则使用第二种方法。 在这种情况下,KeyError将“计数”为一个真正的异常,并将向上传播而不是被此代码捕获,这可能是您想要的。 使用包含许多except子句的长try块会导致在您实际上不想捕获它们时捕获错误。 但是,如果你真的想要捕获任何指定的异常,那么拥有这样的块是有意义的,无论它出现在块中的哪个位置。


They do different things, so which one you use depends on what you're trying to do. The first one catches any error in any of the four lines inside the try block that matches &any* of the except clauses. The second version only catches one kind of exception per line of "tried" code. For instance, the first version will catch a KeyError if one is raised from the line entity1 = Entity1.objects.get(id=1); the second version will not catch such an error, since there is no except KeyError clause for that line.

That said, in general it's a good idea to keep try blocks short. If the only error you want to handle for the first line is Entity1.DoesNotExist, then use the second approach. In this case, a KeyError will "count" as a real exception and will propagate upwards instead of being caught by this code, which is probably what you want. Using long try blocks with lots of except clauses can result in errors being caught when you didn't actually want to catch them. However, it can make sense to have such blocks if you really do want to catch any of the specified exceptions, no matter where in the block it occurs.

相关问答

更多
  • ftp中的位基于数据报,因此它们通过固定路径以特定大小的数据包发送。 要发送所有数据,您需要确定整个文件的大小,然后在ftp端预期相同。 更好的方法是在文件末尾添加结束分隔符。 因此,当您遍历ftp端的文件内容并找到结束分隔符时,您必须停止期望来自同一客户端的文件中的更多数据。 保持单次发送中传输的位的标称大小约为1024,由于各种原因,这是首选大小(请在Google上找到原因,您可以轻松找到它)。 The bits in the ftp are based on datagrams, so they ar ...
  • 请参阅en.wikipedia.org/wiki/JPEG。 它说“在子采样之后,每个通道必须分成8×8块。根据色度子采样,这产生(最小编码单元)MCU块大小为8×8(4:4:4 - 无子采样),16×8 (4:2:2),或最常见的是16×16(4:2:0)。 Please refer en.wikipedia.org/wiki/JPEG. It says "After subsampling, each channel must be split into 8×8 blocks. Depending on ...
  • 我已经达到的“最干净”(即不依赖于外部卷和最可重用)的Python解决方案是打开设备文件并在最后查找,返回文件偏移量: def get_file_size(filename): "Get the file size by seeking at end" fd= os.open(filename, os.O_RDONLY) try: return os.lseek(fd, 0, os.SEEK_END) finally: os.close(fd) ...
  • 你可以在/proc/cpuinfo找到它; 总大小的cache size ,以及块大小的cache_alignment 。 You can find it in /proc/cpuinfo; cache size for the total size, and cache_alignment for the block size.
  • 他们做不同的事情,所以你使用哪一个取决于你想要做什么。 第一个捕获try块中四行中任何匹配& except * except子句中的任何错误。 第二个版本每行“尝试”代码只捕获一种异常。 例如,如果从行entity1 = Entity1.objects.get(id=1) ,则第一个版本将捕获entity1 = Entity1.objects.get(id=1) ; 第二个版本不会捕获这样的错误,因为except KeyError该行的except KeyError子句except KeyError没有。 ...
  • 您可以使用CLI: hadoop fs -D dfs.block.size=file-size -put local_name remote_location 或者,如果要创建或复制文件,可以使用Java API指定dfs.block.size。 Configuration conf = new Configuration(); conf.setInt("dfs.block.size",file-size); you can use CLI: hadoop fs -D dfs.block.size=fi ...
  • 这里已经回答了类似的问题: 在一行命令行中执行Python多行语句 。 简而言之,使用有趣的$''引用(它解释像\n这样的转义)应该起作用,至少在bash中是这样的: $ cat json.txt {"item": [{"id": 1}]} $ cat json.txt | python -c $'import sys, json;\nd=json.load(sys.stdin)\nif len(d["item"])==1: print("""1 item:\n%s""" % d["item"][0][" ...
  • 我只能提供一些一般性建议,因为很多将取决于实际用例: 对齐 :我想池应确保其中的对象正确对齐。 这意味着您可能希望将对象放置在至少是std::alignment_of::value或alignof(T)的倍数的内存位置。 缓存友好性 :池还可以将对象位置向上舍入到缓存行大小的倍数,因此(小)对象永远不会放置在两个缓存行中,而是始终位于单个缓存行中。 填充 :如果对象非常小(只有几个字节),但是你有很多对象,那么任何额外的填充都可能会增加内存需求,这取决于应用程序是否会出现问题。 当对象没有保持在靠近的 ...
  • 块大小64MB表示块的上限大小。 这并不意味着小于64MB的文件块将消耗64MB。 它不会消耗64MB来存储1MB的大块。 如果文件是160兆字节 , 希望这可以帮助。 Block size 64MB means an upper bound size for a block. It doesn't mean that file blocks less than 64MB will consume 64MB. It will not consume 64MB to store a chunk of 1MB. ...
  • 当当前符号缓冲区填满(默认为16,383个符号)或输入数据完成(请求Z_FINISH )时,zlib的deflate结束块。 zlib中的deflate不会尝试判断何时更早结束块可能是有益的。 在这种情况下,一个符号是一个文字,或任何长度的一个匹配。 符号缓冲区的大小由deflateInit2()的memLevel参数确定。 memLevel为8,这是deflateInit()使用的默认值,产生16,383个符号。 memLevel可以是1到9,其中符号缓冲区大小为(1 << (memLevel + 6)) ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。