안녕하세요 선생님 저번에 질문드렸엇던사람입니다.
컨트롤이 데이터 바인딩된 경우에는 DataGridView의 행 컬렉션에 프로그래밍 방식으로 행을 추가할 수 없습니다 라는오류가 발생하였는데
방법을 여기저기 찾아보고알아봤는데도 잘되지가않아서질문드립니다..
namespace MultiChatServer {
public partial class ChatForm : Form {
delegate void AppendTextDelegate(Control ctrl, string s);
AppendTextDelegate _textAppender;
Socket mainSock;
IPAddress thisAddress;
public ChatForm() {
InitializeComponent();
mainSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
_textAppender = new AppendTextDelegate(AppendText);
DataTable table = new DataTable();
table.Columns.Add("F");
table.Columns.Add("Number", typeof(int));
table.Columns.Add("Data", typeof(float));
table.Columns.Add("E");
dataGridView1.DataSource = table;
}//선언
void AppendText(Control ctrl, string s) {
if (ctrl.InvokeRequired) ctrl.Invoke(_textAppender, ctrl, s);
else
{
string source = ctrl.Text;
ctrl.Text = source + Environment.NewLine + s;
}
}
void OnFormLoaded(object sender, EventArgs e) {
IPHostEntry he = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress addr in he.AddressList) {
if (addr.AddressFamily == AddressFamily.InterNetwork) {
thisAddress = addr;
break;
}
}
if (thisAddress == null)
thisAddress = IPAddress.Loopback;
txtAddress.Text = thisAddress.ToString();
}
void BeginStartServer(object sender, EventArgs e) {
int port;
if (!int.TryParse(txtPort.Text, out port)) {
MsgBoxHelper.Error("포트 번호가 잘못 입력되었거나 입력되지 않았습니다.");
txtPort.Focus();
txtPort.SelectAll();
return;
}
IPEndPoint serverEP = new IPEndPoint(thisAddress, port);
mainSock.Bind(serverEP);
mainSock.Listen(10);
mainSock.BeginAccept(AcceptCallback, null);
}
List<Socket> connectedClients = new List<Socket>();
void AcceptCallback(IAsyncResult ar) {
Socket client = mainSock.EndAccept(ar);
mainSock.BeginAccept(AcceptCallback, null);
AsyncObject obj = new AsyncObject(4096);
obj.WorkingSocket = client;
connectedClients.Add(client);
AppendText(txtHistory, string.Format("사용자 (@ {0})가 연결되었습니다.", client.RemoteEndPoint));
client.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
}
void DataReceived(IAsyncResult ar) {
AsyncObject obj = (AsyncObject)ar.AsyncState;
//예외처리 구문 (튕김방지)
string text = Encoding.UTF8.GetString(obj.Buffer);
string[] tokens = text.Split(' ');
string ip = tokens[0];
string msg = tokens[0];
AppendText(txtHistory, string.Format("[받음]{0}: {1}", ip, msg));
for (int i = connectedClients.Count - 1; i >= 0; i--) {
Socket socket = connectedClients[i];
if (socket != obj.WorkingSocket) {
try { socket.Send(obj.Buffer); }
catch {
try { socket.Dispose(); } catch { }
connectedClients.RemoveAt(i);
}
}
}
try
{
int received = obj.WorkingSocket.EndReceive(ar);
}
catch (Exception e)
{
string Message = "서버가 끊어졌습니다" + e.Message;
MessageBox.Show(Message);
return;
}
obj.ClearBuffer();
obj.WorkingSocket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
}
void OnSendData(object sender, EventArgs e) {
if (!mainSock.IsBound) {
MsgBoxHelper.Warn("서버오프라인 상태");
return;
}
string tts = txtTTS.Text.Trim();
if (string.IsNullOrEmpty(tts)) {
MsgBoxHelper.Warn("텍스트가 입력되지 않았습니다!");
txtTTS.Focus();
return;
}
byte[] bDts = Encoding.UTF8.GetBytes(thisAddress.ToString() + '\x01' + tts);
for (int i = connectedClients.Count - 1; i >= 0; i--) {
Socket socket = connectedClients[i];
try { socket.Send(bDts); } catch {
try { socket.Dispose(); } catch { }
connectedClients.RemoveAt(i);
}
}
AppendText(txtHistory, string.Format("[보냄]{0}: {1}", thisAddress.ToString(), tts));
txtTTS.Clear();
}
private void lblPort_Click(object sender, EventArgs e)
{
}
private void txtHistory_TextChanged(object sender, EventArgs e)
{
string[] lines = txtHistory.Lines;
string[] row0 = { "", "", "", "" };
dataGridView1.Rows.Add(row0);
dataGridView1.DataSource = lines;
}
private void lblAddress_Click(object sender, EventArgs e)
{
}
private void tblMainLayout_Paint(object sender, PaintEventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
txthistory쪽에 클라이언트측에서 발신되는 채팅창에 수식을넣어줌으로써 자동으로 데이터그리드뷰로 이동하려고하는데 이와같은오류가 뜨는데 무엇이문제일까요...
[최초 등록일: ]
[최종 수정일: 9/26/2022]