在dataGrid的CurrentCellChanged事件中写事件不知下例对你有无用处:private void dataGrid1_CurrentCellChanged(object sender, System.EventArgs e)
{
int x=this.dataGrid1.CurrentCell.RowNumber; //取行号
//int y=this.dataGrid1.CurrentCell.ColumnNumber; //取列号
MessageBox.Show(this.dataGrid1[x,0].ToString());//显示X行0列的值
}

解决方案 »

  1.   

    那怎么取出这个CurrentCell的值和设定它的值呢?
      

  2.   

    自己顶一下了。怎么取出这个CurrentCell的值和设定它的值呢?
      

  3.   

    给你一个自适应列宽的例子:
    string connString = "server=localhost;database=hos;uid=sa;pwd=";
    string sqlString = "SELECT * FROM ME_EXCEPREG"; DataSet _dataSet = null; try
    {
    // Connection object
    System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connString); // Create data adapter object
    System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlString, connection);

    // Create a dataset object and fill with data using data adapter's Fill method
    _dataSet = new DataSet();
    dataAdapter.Fill(_dataSet, "ME_EXCEPREG");
    connection.Close();
    }
    catch(Exception ex)
    {
    MessageBox.Show("Problem with DB access-\n\n   connection: "
    + connString + "\r\n\r\n            query: " + sqlString
    + "\r\n\r\n\r\n" + ex.ToString());
    this.Close();
    return;
    } // Create a table style that will hold the new column style 
    // that we set and also tie it to our customer's table from our DB
    DataGridTableStyle tableStyle = new DataGridTableStyle();
    tableStyle.MappingName = "ME_EXCEPREG"; // make the dataGrid use our new tablestyle and bind it to our table
    dataGrid1.TableStyles.Clear(); dataGrid1.TableStyles.Add(tableStyle);
    dataGrid1.DataSource = _dataSet.Tables["ME_EXCEPREG"];
      

  4.   

    以上是取数据,
    下面是
    public void AutoSizeTable()
    {
    int numCols = ((DataTable) dataGrid1.DataSource).Columns.Count;
    for(int i = 0; i < numCols; ++i)
    AutoSizeCol(i);
    }
    public void AutoSizeCols(int start, int finish)
    {
    for(int i = start; i <= finish; ++i)
    AutoSizeCol(i);
    }
    public void AutoSizeCol(int col)
    {
    float width = 0;
    int numRows = ((DataTable) dataGrid1.DataSource).Rows.Count;

    Graphics g = Graphics.FromHwnd(dataGrid1.Handle);
    StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
    SizeF size; for(int i = 0; i < numRows; ++ i)
    {
    size = g.MeasureString(dataGrid1[i, col].ToString(), dataGrid1.Font, 500, sf);
    if(size.Width > width)
    width = size.Width;
    } g.Dispose(); dataGrid1.TableStyles["ME_EXCEPREG"].GridColumnStyles[col].Width = (int) width;
    }